BUG: A BadImageFormatException exception may occur when you use a recursively defined constraint of a generic type in a .NET Framework 2.0-based application

This article has been archived. It is offered "as is" and will no longer be updated.
Symptoms
In a Microsoft .NET Framework 2.0-based application, you use a recursively defined constraint of a generic type. When you do this, a BadImageFormatException exception may occur at run time. This problem occurs only in certain scenarios.
Cause
This problem occurs because of an issue in the Microsoft Visual Studio 2005 common language runtime (CLR 2.0) components.
Workaround
To work around this problem, remove the class constraint from the public static E GetClass<E> method.

Note Constraints are limits that are put on generic-type parameters.

To remove the class constraint from the public static E GetClass<E> method, change the method signature as follows.

Existing code

public static E GetClass<E>() where E : class, new()

Replacement code

public static E GetClass<E>() where E : new()
Status
Microsoft has confirmed that this is a bug in the Microsoft products that are listed in the "Applies to" section.
More information
For more information about generics in the CLR, visit the following Microsoft Developer Network (MSDN) Web site:

Steps to reproduce the problem

  1. On a computer that has Visual Studio 2005 installed, create the following C# program.
    using System;public abstract class AbstractClass1<E> where E : AbstractClass1<E>, new(){ }public class Class1 : AbstractClass1<Class1>{ }public class Class2<E> where E : AbstractClass1<E>, new(){    public E GetClass1()    {        return Factory.GetClass<E>();    }}public class Factory{    public static E GetClass<E>() where E : class, new()    {        return new E();    }}public class Program{    static void Main()    {        Console.WriteLine("Hit enter to continue..");        Console.ReadLine();        Class2<Class1> c2 = new Class2<Class1>();        c2.GetClass1();        Console.WriteLine("Hi");    }}
  2. Compile the program, and then run the program. The BadImageFormatException exception occurs at run time when the c2.GetClass1 method is called.
Properties

Article ID: 940164 - Last Review: 01/16/2015 10:57:00 - Revision: 2.0

  • Microsoft .NET Framework 2.0
  • Microsoft Visual Studio 2005 Standard Edition
  • Microsoft Visual Studio 2005 Professional Edition
  • kbnosurvey kbarchive kbbug kbtshoot KB940164
Feedback