#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.

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: