Do not mix method hiding with method overriding. They are two completely different beasts.
When hiding a method, you are only hiding it when accessing the method through the type that hides the method to begin with:
public class Foo
{
public string Blah() { return "Hi from Foo!"; }
}
public class DerivedFoo: Foo
{
public new string Blah() { return "Hi from DerivedFoo!"; }
}
Now we have the following behavior:
void TestFoos()
{
Foo foo = new Foo();
DerivedFoo derivedFoo = new DerivedFoo();
Foo derivedFooInDisguise = derivedFoo as Foo;
Console.WriteLine(foo.Blah()); //Outputs "Hi from Foo!"
Console.WriteLine(derivedFoo.Blah()); //Outputs "Hi from DerivedFoo!"
Console.WriteLine(derivedFooInDisguise.Blah()); //Outputs "Hi from Foo!"
}
Note, that this behavior is the same even if Blah
is declared as virtual
. The interesting part is the third call. The method is invoked through a Foo
typed object. As its not a virtual call, Foo.Blah()
is called, not DerivedFoo.Blah()
.
Now this is completely different from method overriding where the virtual method call always resolves to the runtime type of the object, not the type through which you are calling it:
public class Foo
{
public virtual string Blah() { return "Hi from Foo!"; }
}
public class DerivedFoo: Foo
{
public override string Blah() { return "Hi from DerivedFoo!"; }
}
Now we have the following behavior:
void TestFoos()
{
Foo foo = new Foo();
DerivedFoo derivedFoo = new DerivedFoo();
Foo derivedFooInDisguise = derivedFoo as Foo;
Console.WriteLine(foo.Blah()); //Outputs "Hi from Foo!"
Console.WriteLine(derivedFoo.Blah()); //Outputs "Hi from DerivedFoo!"
Console.WriteLine(derivedFooInDisguise.Blah()); ////Outputs "Hi from DerivedFoo!"
}