#1,105 – Re-Declaring a Class-Level Variable within a Method

You can re-declare a class-level variable within a method, that is–declare a local variable having the same name as a class-level variable.  Within the scope of the method, the local variable will hide the class-level variable.

    public class MyClass
    {
        public int x = 10;

        public void MethodA()
        {
            double x = 4.2;
            Console.WriteLine(x);
        }
    }

1105-001
You cannot, however, reference a class-level variable before declaring the local variable, since this is interpreted as referencing the local variable before it is defined.

        public void MethodA()
        {
            // ERROR: Can't use local variable before it's declared
            Console.WriteLine(x);

            double x = 4.2;
            Console.WriteLine(x);
        }

You also can’t reference the class-level variable in an outer scope.

        public void MethodA()
        {
            Console.WriteLine(x);

            if (DateTime.Now.DayOfWeek == DayOfWeek.Tuesday)
            {
                // ERROR: Can't declare local variable within this scope
                double x = 4.2;
                Console.WriteLine(x);
            }
        }
Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

4 Responses to #1,105 – Re-Declaring a Class-Level Variable within a Method

  1. Pingback: Dew Drop – May 28, 2014 (#1785) | Morning Dew

  2. Peter says:

    Hi,

    Not sure if this is something you plan on covering in on a future day, but you can reference the class level variable by prefixing it with “this”, in your example it would be

    // ERROR: Can’t use local variable before it’s declared, unless you prefix it with this
    Console.WriteLine(this.x);

    Though this is ugly, and why there are people who prefix class level variables with an underscore to prevent method / class variables conflicting, particularly when initialising from the constructor.

    Cheers,
    Peter

  3. Steve says:

    Wrong on your second example. If x is a field of the class, Console.WriteLine(x); is OK because x is the reference variable instead of local variable.

    public class MyClass
    {
    public int x = 10;

    public void MethodA()
    {
    // ERROR: Can’t use local variable before it’s declared
    Console.WriteLine(x);

    double x = 4.2;
    Console.WriteLine(x);
    }

    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: