Search code examples
c#enumscls-compliantassemblybuilder

Does EnumBuilder always create enum which are not CLS-Compliant ? How to make the enum CLS compliant?


Below code sample generates TempAssembly.dll with an enum Elevation in it.

 public static void Main()
        {
            AppDomain currentDomain = AppDomain.CurrentDomain;
            AssemblyName aName = new AssemblyName("TempAssembly");
            AssemblyBuilder ab = currentDomain.DefineDynamicAssembly(aName, AssemblyBuilderAccess.RunAndSave);
            ModuleBuilder mb = ab.DefineDynamicModule(aName.Name, aName.Name + ".dll");
            EnumBuilder eb = mb.DefineEnum("Elevation", TypeAttributes.Public, typeof(int));
            eb.DefineLiteral("Low", 0);
            eb.DefineLiteral("High", 1);
            Type finished = eb.CreateType();
            ab.Save(aName.Name + ".dll");
            foreach (object o in Enum.GetValues(finished))
            {
                Console.WriteLine("{0}.{1} = {2}", finished, o, ((int)o));
            }
        }

I referenced TempAssembly.dll and used the enumeration Elevation in another project(say project TestA). As I want the code to be CLS-Compliant I added the following attribute to the project TestA.

[assembly:System.CLSCompliant(true)]

The code where I am getting warning is:

public class TestClass
{
    public Elevation Elev { get; set; } 
}

The warning

Warning 1 Type of 'TestA.TestClass.Elev' is not CLS-compliant

I checked documentation on how to write CLS Compliant code but I am unable to do much as the enum is being created dynamically. Any suggestions , how can I make the enum CLS compliant?


Solution

  • Have you tried marking the assembly as CLS-compliant?

    ab.SetCustomAttribute(new CustomAttributeBuilder(
            typeof(CLSCompliantAttribute).GetConstructor(new[] { typeof(bool) }),
            new object[] { true }));
    

    You should be able to do the same on eb too:

    eb.SetCustomAttribute(new CustomAttributeBuilder(
            typeof(CLSCompliantAttribute).GetConstructor(new[] { typeof(bool) }),
            new object[] { true }));