views:

557

answers:

2

I want to create a class with a nested enum.

public class Foo
{
    public enum Views
    {
    }
}

However System.Reflection.Emit.TypeBuilder class has no DefineNestedEnum only DefinedNestedType. ModuleBuilder.DefineEnum exists that let's me create an enum but I find no way to make it nested. Can I create an enum without faking it (i.e., using EnumBuilder)?


I moved my solution to an answer below.

+2  A: 

See the example at the end of this article, which does exactly what you want. (You use DefineNestedType with the right arguments)

jlew
How is that different from what I said? A nested type that inherits from System.Enum with define fields with constant values.That MSDN example would, however, seem to indicate that there is no inherit support for creating nested enums.
Colin Burnett
The point is: that is what a nested enum is -- a nested type that inherits from System.Enum which defines fields with constant values.Take a look in reflector at what that MSDN sample produces in its emitted assembly, and compare it to a nested enum produced by compiling a C# class with a nested enum, and you'll find that are identical.
jlew
Again, how is the MSDN article you linked different than what I had originally posted in the question (and since moved to an answer)?My question isn't about how to fake an enum (I clearly got that covered). EnumBuilder exists to cover up all the details of what an enum really is but I find no way to get an EnumBuilder and have it nested.
Colin Burnett
Your question asks how you do it "without faking it". There is nothing fake about that solution, it produces an honest-to-goodness enum. There apparently is no convenience method using EnumBuilder to do the same thing, which MS has acknowledged by giving you slightly more complicated code to achieve the same result.
jlew
+1  A: 

Moving my answer I put in the question to here.


Only thing I can think of is to define a nested type as sealed class that extends System.Enum and define public|static|literal fields with constant values. This is essentially what the C# compiler is doing based on what I've learned by disassembling it. If I do this and reference the assembly Intellisense recognizes it as an enum and functions just like an enum.


This is exactly the method MSDN shows that Jeremy linked.

Colin Burnett