2012-11-12

C# Blooper №5: Lame/annoying variable scoping rules, Part 2


Before reading any further, please read the disclaimer.

In light of the previous blooper, this one is more of a confusing error message than an actual new blooper. What I am doing below is that I am declaring a field within a class, I am accessing that field from within a method, and further down within the same method I am declaring a new local variable with the same name as the field. Now, C# will not allow me to declare that local variable because it has the same name as the field, but that's not where I am receiving the error. Instead, the error is given when accessing the field. If you only read the first sentence of the error message, it does not make any sense at all. If you bother also reading the second sentence, it gives you a hint as to the real problem. Now, that's not very cool.

namespace Test5
    {
        public class Test
        {
            public int a;

            void foo()
            {
                for( int i = 0;  i < 10;  i++ )
                {
                    a = 10; //error CS0844: Cannot use local variable 'a' before it is declared. The declaration of the local variable hides the field 'Test5.Test.a'.
                }
                string a = "";
                Console.WriteLine( a );
            }
        }
    }

See also: C# Blooper №4: Lame/annoying variable scoping rules, Part 1
-

1 comment: