C# Compiler Generating Invalid IL When Dealing With Generics

time to read 11 min | 2130 words

I just had to find out the reason for a strange bug in Rhino Mocks. The issue turned out to be the C# Compiler producing invalid IL, which cause the following error:

failed: System.BadImageFormatException : An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)

Let us start from the beginning, here is an interface and a class:

public interface MyInterface

{

}

 

public class MyGenericClass<I>

{

}

Now, let us define the following test:

public abstract class TestGenericPartialMockBase<I, C> where I : MyInterface where C : MyGenericClass<I>

{

       public void CauseProblem()

       {

              bool val = false;

              if (val)

              {

                     Factory factory = new Factory();

                     object bad = factory.Create<C>();

              }

       }

}

 

[TestFixture]

public class TestGenericPartialMock1 : TestGenericPartialMockBase<MyInterface, MyGenericClass<MyInterface>>

{

       [Test]

       public void TestGenericPartialMockTest1()

       {

              CauseProblem();

       }

}

Notice that the code in the if() clause will never execute, its mere precense cause this error.

The Factory class is simply:

public class Factory

{

       public T Create<T>(params object[] args)

              where T: class

       {

              return null;

       }

}

Put everything in one file and try to run the test, and it will give the error above.

Removing the "where T: class" clause from the Create<T>() method will fix this issue, as well as practically any modification to the code. This is the second time in about three weeks that I see the C# compiler silently issuing invalid IL for complex generic scenario. Interestingly, both scenarios involved inheritance from a generic class.

Update: You can vote on this bug here