I have been recently stumbled by the way the C# compiler resolves the method calls for methods hiding base classes methods. I have written the following tests to expose my problem:
[TestClass]
public class UnitTest1
{
public class Car
{
public int GetNumberOfSeets()
{
return 4;
}
}
public class BmwZ4 : Car
{
public new int GetNumberOfSeets()
{
return 2;
}
}
[TestMethod]
public void TestBmwNumberOfSeets1()
{
BmwZ4 bmw = new BmwZ4();
Assert.AreEqual(2, bmw.GetNumberOfSeets());
}
[TestMethod]
public void TestBmwNumberOfSeets2()
{
var bmw = new BmwZ4();
Assert.AreEqual(2, bmw.GetNumberOfSeets());
}
[TestMethod]
public void TestBmwNumberOfSeets3()
{
Car bmw = new BmwZ4();
Assert.AreEqual(2, bmw.GetNumberOfSeets());
}
}
Surprisingly TestBmwNumberOfSeets1 and TestBmwNumberOfSeets2 are working perfectly fine where as TestBmwNumberOfSeets3 is just not working.
Can somebody explain to me why using a Car as the receiving type (implicit upcast) will transform my brand new BMW into a simple Car?
EDIT: I understood that by using the hiding mechanism, the method that will be called depends on the type of the variable calling the method. There is no dynamic dispatch. But why? It would have been easy for the compiler to use the dynamic type instead of the statically declared one.
The hiding mechanism in my mind is to be used when one want to override a class which is not sealed and does not belong to him (using a third party API) and wants to create a custom behavior for a method that is not marked virtual. That is the main goal. But if you don't have dynamic dispatch, the feature is purely useless and very dangerous to use.