Search code examples
c#.netoopinheritancepolymorphism

Check if the instance is type of base class or derived class after keyword 'as'?


Please look at the following code:

// Base class
public abstract class Aircraft
{
    public virtual void Fly()
    {
        Console.WriteLine("Aircraft flies");
    }
}

// Derived class
public class Plane : Aircraft
{
    public new void Fly()
    {
        Console.WriteLine("Plane flies");
    }
}

// Execution
public class Program
{
    public static void Main()
    {
        var lPlane = new Plane();
        Console.WriteLine(lPlane.GetType()); // Plane
        lPlane.Fly(); // Plane flies

        var lAircraft = lPlane as Aircraft;
        Console.WriteLine(lAircraft.GetType()); // Plane
        lAircraft.Fly(); // Aircraft flies
    }
}

The following line casts the Plane to an Aircaft:

var lAircraft = lPlane as Aircraft;

So I would expected, that lAircraft is type of Aircraft now. But it isn´t. It is of type Plane:

Console.WriteLine(lAircraft.GetType()); // Plane

How can I check if the current instance is type of base class or derived class after cast by the keyword as?


Solution

  • This code:

    var lAircraft = lPlane as Aircraft;
    

    Will be compiled to this:

    Aircraft aircraft = lPlane;
    

    So that means the as keyword here do nothing because you can't convert your derived class to it's base class. To find out more you can read this answer: https://stackoverflow.com/a/8329517/2946329