sikka karma
sikka karma

Reputation: 115

How to use global variable from inside a function if already have a local variable with same name


using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Globalization;
    namespace tesitingInMyKitchen
    {
        class program
        {
           static string cheese = "chedar";

            static void Main()
            {
                string cheese = "swiss";
                //printing local cheese
                Console.WriteLine(cheese);
                //here want to print global cheese 
                Console.WriteLine(global :cheese);
            }
        }
    }

Upvotes: 0

Views: 1867

Answers (2)

Dirk Trilsbeek
Dirk Trilsbeek

Reputation: 6023

your "global variable"

static string cheese = "chedar";

is not a global variable but a static property of the class program. You can therefore access it this way:

Console.WriteLine(program.cheese);

please note that, as you haven't explicitly defined an access modifier (public, protected, internal or private) on your static property, access is by default limited to members of the class the property is defined in (implicit private declaration), while the class program itself is by default decleared internal. So this property cheese may be available to all methods within your class program, but it is not available to any member of any other class, including classes that inherit from program.

Upvotes: 6

ashin
ashin

Reputation: 2603

For static field, use ClassName.FieldName, if it's non-static, you could use 'this' keyword: this.FieldName

class MyClass
{       
    static string cheese = "chedar";
    string cheese1 = "global";

    void Main()
    {
        string cheese = "swiss";
        string cheese1 = "local";

        Console.WriteLine(cheese);
        Console.WriteLine(MyClass.cheese);

        Console.WriteLine(cheese1);
        Console.WriteLine(this.cheese1);
    }
}

Upvotes: 1

Related Questions