#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