-2

I have the following code:

   class Animal
    {
        public virtual void Invoke()
        {
            Console.WriteLine("Animal");
        }
    }
    class Dog : Animal
    {
        public override void Invoke()
        {
            Console.WriteLine("Dog");
        }
    }
    class Dobberman : Dog
    {
        public new void Invoke()
        {
            Console.WriteLine("Dobberman");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Animal dog = new Dobberman();
            dog.Invoke();
            Dobberman dog2 = new Dobberman();
            dog2.Invoke();
        }
    }

Why would it print "Dog" in the first output? and why "Dobberman" in the second? What is going on under the hood?

Ardavazt
  • 29
  • 5

1 Answers1

-1

Invoke is virtual on Animal, is overridden by Dog, and hidden by Dobberman (SIC)

Remember that methods are bound at compile time, then looks for overrides at runtime for virtual methods.

So the binding is as follows:

Animal dog = new Dobberman(); 
// binds to Dog.Invoke since the variable type is Animal, 
// the runtime type is Dog
// and Dog overrides Animal.Invoke
dog.Invoke();  

Dobberman dog2 = new Dobberman();
// binds to Dobberman.Invoke since the variable type is Dobberman
dog2.Invoke(); 
D Stanley
  • 149,601
  • 11
  • 178
  • 240