2

All -

Have read various articles on the new keyword and when it should be used:

MSDN - http://msdn.microsoft.com/en-us/library/6fawty39(v=vs.80).aspx

StackOverflow - benefit of using new keyword in derived class member having same name with base class member

Here is a sample code I have written to practice this concept

    static void Main(string[] args)
    {
        Animal a2 = new Dog();
        a2.Talk();
        a2.Sing();
        a2.Greet();
        a2.Dance();
        Console.ReadLine();
    }

class Animal
{
    public Animal()
    {
        Console.WriteLine("Animal constructor");
    }

    public void Talk()
    {
        Console.WriteLine("Animal is Talking");
    }

    public virtual void Sing()
    {
        Console.WriteLine("Animal is Singing");
    }

    public void Greet()
    {
        Console.WriteLine("Animal is Greeting");
    }

    public virtual void Dance()
    {
        Console.WriteLine("Animal is Dancing");
    }
}

//Derived Class Dog from Animal
class Dog : Animal
{
    public Dog()
    {
        Console.WriteLine("Dog Constructor");
    }

    public new void Talk()
    {
        Console.WriteLine("Dog is Talking");
    }

    public override void Sing()
    {
        //base.Sing();
        Console.WriteLine("Dog is Singing");
    }

    public new void Dance()
    {
        Console.WriteLine("Dog is Dancing");
    }
}

Any my output is coming as follows:

enter image description here

Whats confusing me is that by using the new keyword in the derieved class is actually showing an output of the base class. Isnt that wrong - isnt new keyword supposed to hide the base class membership so the result for Animal is Talking and Animal is Dancing should not be printed.

Thanks

Community
  • 1
  • 1
Patrick
  • 864
  • 1
  • 14
  • 27

2 Answers2

7

The "new" means the method is "new" and not an "override". Therefore, if you call a method by that name from the base, it hasn't been overriden so the derived won't be called.

Peter Ritchie
  • 35,463
  • 9
  • 80
  • 98
0

This was confusing to me as well but to put it simply:

The new keyword hides the child's member from the parent.

Exocomp
  • 1,477
  • 2
  • 20
  • 29