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