#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)
Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

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 )

Connecting to %s

%d bloggers like this: