#709 – A Method Can Redefine a Name Present in Parent Class

Variables declared within the scope of a method can have the same name as a member of the class in which the method is declared.

For example:

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

        public void Bark()
        {
            string Name = "Loud Bark";

            Console.WriteLine(string.Format("{0}: WOOF!", Name));
            Console.WriteLine(this.Name);
        }
    }

Assigning a value to the Name variable within the Bark method has no effect on the Name property defined in the parent class.

Although this is possible in C#, reusing names in this way is not a good idea because:

  • It can lead to confusion for someone trying to understand the code
  • The method can no longer access the identically named member from the parent class (without using the this keyword)
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: