Search code examples
c#typescompile-timecompile-time-type-checking

Checking object's compile-time type in C#


Consider the following code:

using System;
                    
public class Program
{
    public static void Main()
    {
        A m1 = new B();
        B m2 = new B();
        
        Console.Write("m1: ");
        m1.fun();
        Console.Write("m2: ");
        m2.fun();
    }
}

abstract class A
{
    public abstract void fun ();
}

class B : A
{
    public override void fun()
    {
        if (this.GetType() == typeof(A)) // ????
            Console.WriteLine("A");
        else Console.WriteLine("B");
    }
}

I want you to modify the if statement so that the program writes A for m1 and B for m2. I've been trying various combinations with GetType(), typeof, is and as, but couldn't make this work.


Solution

  • I'm not sure what the rules of your assignment were, but if you have a virtual method in the base class and override it in the derived, you are always going to get "B".

    If you are allowed to change the inheritance on the types you can do this:

    public class Program
    {
        public static void Main()
        {
            A m1 = new B();
            B m2 = new B();
    
            Console.Write("m1: ");
            m1.Fun();
            Console.Write("m2: ");
            m2.Fun();
    
            // m1: A
            // m2: B
        }
    }
    
    abstract class A
    {
        public void Fun() => Console.WriteLine("A");
    }
    
    class B : A
    {
        public new void Fun() => Console.WriteLine("B");
    }