I'm trying to figure out the concept of shadowing in c#. This is my code, which isn't behaving as I expect it to:
public class Animal
{
public virtual void Foo()
{
Console.WriteLine("Foo Animal");
}
}
public class Dog : Animal
{
public new void Foo()
{
Console.WriteLine("Foo Dog");
}
}
class Program
{
static void Main(string[] args)
{
Dog dog1 = new Dog();
((Animal)dog1).Foo();
Animal dog2 = new Dog();
dog2.Foo();
}
}
When the code in Main
is executed, Foo()
from the base class (Animal
) is called, and from what I read about shadowing, Foo()
from Dog
should be called. Can someone explain what am i missing?
My example is according to this: https://msdn.microsoft.com/en-us/library/ms173153.aspx
UPDATE: This is the example from msdn:
class Program
{
static void Main(string[] args)
{
BaseClass bc = new BaseClass();
DerivedClass dc = new DerivedClass();
BaseClass bcdc = new DerivedClass();
// The following two calls do what you would expect. They call
// the methods that are defined in BaseClass.
bc.Method1();
bc.Method2();
// Output:
// Base - Method1
// Base - Method2
// The following two calls do what you would expect. They call
// the methods that are defined in DerivedClass.
dc.Method1();
dc.Method2();
// Output:
// Derived - Method1
// Derived - Method2
// The following two calls produce different results, depending
// on whether override (Method1) or new (Method2) is used.
bcdc.Method1();
bcdc.Method2();
// Output:
// Derived - Method1
// Base - Method2
}
}
class BaseClass
{
public virtual void Method1()
{
Console.WriteLine("Base - Method1");
}
public virtual void Method2()
{
Console.WriteLine("Base - Method2");
}
}
class DerivedClass : BaseClass
{
public override void Method1()
{
Console.WriteLine("Derived - Method1");
}
public new void Method2()
{
Console.WriteLine("Derived - Method2");
}
}
When bcdc.Method1()
is executed, Method1()
from the derived class gets called, which isn't the case in my example.
In your case,
dog1
which is aDog
will usually get you "Foo Dog", but because you explicitly tell it to be anAnimal
, it displays the "Foo Animal". Makes sense.Then, with the
dog2
, which is anAnimal
, you expect the "Foo animal" to fire, because you said "hey, you're an animal", and even though you havevirtual
onAnimal
(which suggests that deriving classes should override this method, and then the resolution of what to call will happen on run time depending on the type), you use thenew
which hides it.Still perfectly Ok. In their example,
bcdc
is of typeBaseClass
, but at runtime , since it's aDerived
one, ANDMethod1
is usingvirtual
ANDoverride
, on the base and derived, it gets called.Because it's
method2
isn't overriding the virtual, it calls the only one it knows about, the Base one. If instead of defining it asBaseClass
, it would have been aDerivedClass
, it would have found it'smethod2