Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GetFields method to get enum values

  1. I have noticed that when calling GetFields() on enum type, I'm getting an extra fields with type int32. where did it come from??
  2. When I call the other overload (GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static) ), it returns the desired fields. is that means that the enum's fields are not Public ?

thanks

like image 378
eyal Avatar asked Nov 16 '11 09:11

eyal


2 Answers

Reflector IL Spy can explain this.

Take a look at a decompiled enum and you will see something that looks like this:

.class public auto ansi sealed ConsoleApplication1.Foo
    extends [mscorlib]System.Enum
{
    // Fields
    .field public specialname rtspecialname int32 value__
    .field public static literal valuetype ConsoleApplication1.Foo Bar = int32(0)
    .field public static literal valuetype ConsoleApplication1.Foo Baz = int32(1)

} // end of class ConsoleApplication1.Foo

i.e. the Foo enum is implemented as a sealed class that wraps an int32 called value__ - the extra field you are seeing.

Its worth noting that it also inherits from System.Enum which also has extra (static) fields.

like image 74
Justin Avatar answered Nov 02 '22 01:11

Justin


I suspect the field is the underlying value - after all, that value has to be stored somewhere. So an enum like this:

public enum Foo
{
    Bar = 0,
    Baz = 1;
}

is a bit like this:

public struct Foo
{
    public static readonly Bar = new Foo(0);
    public static readonly Baz = new Foo(1);

    private readonly int value;

    public Foo(int value)
    {
        this.value = value;
    }
}
like image 4
Jon Skeet Avatar answered Nov 02 '22 00:11

Jon Skeet