BUG: EnumBuilder Members Are Not Strongly Typed (311092)



The information in this article applies to:

  • Microsoft Common Language Runtime (included with the .NET Framework) 1.0
  • Microsoft .NET Framework Class Libraries 1.0
  • Microsoft .NET Framework 1.0
  • Microsoft Windows .NET Framework 1.1

This article was previously published under Q311092
The following .NET Framework Class Library namespace is referenced in this article:
  • System.R

SYMPTOMS

When you use Reflection Emit to define an enum with ModuleBuilder.DefineEnum, you use EnumBuilder.DefineLiteral to define the members for the enum. The type of the defined members should be the same type as the enum. However, the type is int32.

CAUSE

A bug in the CLR causes the members to be of type int32.

RESOLUTION

To work around this problem, use the TypeBuilder class to define the enum and use the FieldBuilder class to define the members of the enum. The following steps demonstrate how to perform this workaround:
  1. Create a new console application in C# .NET.
  2. Replace all of the code in the module with the following code:
    using System;
    using System.Reflection;
    using System.Reflection.Emit;
    using System.Configuration.Assemblies;
    
    
    class EnumBuilderWorkaround
    {
    	public static void Main()
    	{
    String g = "MyAssembly";
    		AssemblyName asmname = new AssemblyName();
    		asmname.Name = g;
    
    		AssemblyBuilder asmbuild = System.Threading.Thread.GetDomain().
    			DefineDynamicAssembly(asmname, AssemblyBuilderAccess.RunAndSave);   // Run and save only assembly.
    
    		ModuleBuilder mod = asmbuild.DefineDynamicModule("Mod1", asmname.Name + ".dll" );
    	
    
    		TypeBuilder tb = mod.DefineType( "myenum", TypeAttributes.Public | TypeAttributes.Sealed,
    							typeof(Enum) );
    		tb.DefineField( "value__", typeof(int),
    					FieldAttributes.Private | FieldAttributes.SpecialName |
    						FieldAttributes.RTSpecialName );
    FieldBuilder fb = tb.DefineField( "myfield1", tb,
    					FieldAttributes.Public | FieldAttributes.Static | FieldAttributes.Literal );
    
    		fb.SetConstant( 1 );
    
    		tb.CreateType();
    
    		Console.WriteLine( asmname.Name + ".dll" );
    		asmbuild.Save( asmname.Name + ".dll" );
    
    		
    	}
    }
    					
  3. Save, build, and then execute the console application.
  4. View the Debug/Bin directory in the application directory. MyAssembly.dll is built and placed in this directory.
  5. Use Ildasm.exe to open MyAssembly.dll.
  6. Expand the myenum node. Note that myfield1 is of type myenum and not of type int32.

STATUS

Microsoft has confirmed that this is a bug in the Microsoft products that are listed at the beginning of this article.

Modification Type:MinorLast Reviewed:5/28/2003
Keywords:kbbug kbfix kbreadme KB311092