Can obj.GetType().IsInterface be true?

While doing something almost completely irrelevant, a question popped into my head:

Can an expression of the form obj.GetType().IsInterface ever be true in a codebase consisting exclusively of C# code?

I suspect the answer is no, because:

  • GetType() will always return the runtime type.
  • The runtime type for concrete types matches the invoked constructor. Thus, it is never an interface, because interfaces don't have constructors.
  • Anonymous types cannot implement an interface (and if they did, they'd still have their anonymous class type).
  • Instances of internal classes of other assemblies implementing public interfaces will still have the class as the runtime type.
  • Using [ComImport, CoClass(typeof(MyClass))] on an interface makes it look like you can instantiate it, but the constructor call actually instantiates the referenced class.

I can't think of any other case. Am I missing something, or is my guess correct?

Jon Skeet
people
quotationmark

Can an expression of the form obj.GetType().IsInterface ever be true in a codebase consisting exclusively of C# code?

Yes - but probably not the way you were thinking of:

using System;

public class EvilClass
{
    public new Type GetType()
    {
        return typeof(IDisposable);
    }
}

class Test
{
    static void Main()
    {
        EvilClass obj = new EvilClass();
        Console.WriteLine(obj.GetType().IsInterface); // True
    }
}

Slightly similarly, I believe you could create a subclass of RealProxy which would intercept the call and return an interface type.

If you mean "will the return value of the GetType() method declared in object ever be an interface type" - in that case I suspect the answer is no.

people

See more on this question at Stackoverflow