#721 – Local Variable Declarations Can Hide Class Members

It’s possible to declare a variable in a method that has the same name as one of the class members in the class where the method is defined.  The local variable is said to hide the class member.

    public class Dog
    {
        public string Name { get; set; }

        public Dog(string name)
        {
            Name = name;
        }

        public void Bark()
        {
            // Local variable Hides Dog's Name property
            string Name = "Franklin Roosevelt";

            Console.WriteLine(string.Format("{0} says WOOF", Name));

            // Can still access Dog.Name via this pointer
            Console.WriteLine(string.Format("I'm {0}", this.Name));
        }
    }


Notice that you can still access the class-level Name property by using the this keyword.

While it’s possible to hide a class member in this way, it’s generally considered to be bad practice.  When you make Name mean different things, depending on what part of the code you’re in, this can lead to confusion.

Advertisement