Regarding this this post, it seem not to be possible to cast an derived class to it´s base class by the keyword as
.
In the code of that post is used the keyword override
. But when I use instead the keyword new
, then the cast to the base-class becomes visible:
// base class
public class Aircraft
{
public virtual void fly()
{
Console.WriteLine("Aircraft flies");
}
}
// derived class
public class Plane : Aircraft
{
public new void fly()
{
Console.WriteLine("Plane flies");
}
}
public class Program
{
public static void Main()
{
var plane = new Plane();
Console.WriteLine(plane.GetType()); // "Plane"
plane.fly(); // "Plane flies"
var aircraft = plane as Aircraft; // <-- cast to base class
Console.WriteLine(aircraft.GetType()); // "Plane"
aircraft.fly(); // "Aircraft flies"
}
}
The code aircraft.GetType();
indicates that the cast to the base class didn´t happen. It´s still a Plane
. But aircraft.fly();
says, that the cast to the base class worked, because the method says: "Aircraft flies".
Who can solve my confusion?