Search code examples
c#.netinterfaceclrmethod-dispatch

How are interface types loaded by the CLR?


Does the CLR Load interface types if they are not initialized with Concrete implementations?

Considering an interface IFoo which has an implementation FooImpl

e.g.

IFoo foo;

as opposed to

IFoo foo = new FooImpl();

Will the CLR only load the IFoo Type in the second case? Also if there is a another type which inherits from FooImpl (e.g. FooImpl2)

Will this code start from FooImpl2 and walk up the inheritance hierarchy to load IFoo interface? Also, will the IFoo's MethodTable contain a pointer directly to the FooImpl2's method table or will it redirected via the intermediate implementing type (ie FooImpl).

IFoo foo = new FooImpl2();

Solution

  • This line of code

    IFoo foo;
    

    says that the foo is a variable that can hold a reference to an object that implements the interface IFoo.

    Will the CLR only load the IFoo Type in the second case?

    In the second case you create an object of type FooImpl and you make use of a variable called foo that stores a reference to this object. In order for a variable to hold a reference to an object, the variable's type should be compliant to this object. Saying compliant, I mean that either the variable's type would be the same as the object you create or would be a base type or an interface. That being said there isn't any load of any interface.

    This line of code:

    IFoo foo = new FooImpl();
    

    says that the foo will hold a reference to an object that implements the IFoo interface, just this.

    Also if there is a another type which inherits from FooImpl (e.g. FooImpl2) Will this code start from FooImpl2 and walk up the inheritance hierarchy to load IFoo interface?

    No

    Also, will the IFoo's MethodTable contain a pointer directly to the FooImpl2's method table or will it redirected via the intermediate implementing type (ie FooImpl).

    The reference that will be stored in the variable would point to the FooImpl2's method table direclty. Actually, it would point to the concrete object stored in heap and there would be the reference to the method's table of FooImpl2.