Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can obj.GetType().IsInterface be true?

Tags:

c#

reflection

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?

like image 969
Theodoros Chatzigiannakis Avatar asked Aug 30 '14 16:08

Theodoros Chatzigiannakis


1 Answers

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.

like image 178
Jon Skeet Avatar answered Oct 18 '22 18:10

Jon Skeet