1

Possible Duplicate:
Getting Enum value via reflection

With mytype.ReflectedType.GetFields() I can get the constants defined in a c# class.

how can I get with mytype.ReflectedType.XXX a certain enum I have defined inside the c# class during runtime?

Community
  • 1
  • 1
msfanboy
  • 5,273
  • 13
  • 69
  • 120
  • I do not know the enum during compile time. This is not a duplicate! – msfanboy Sep 10 '12 at 12:05
  • That's why it says Possible Duplicate ;-) FWIW if you can enumerate the members of the class, then this answer (and the answer from Marc Gravell) may be helpful: http://stackoverflow.com/a/5006004/1073107 – dash Sep 10 '12 at 12:21
  • Your edit also changes the question a lot :-) Can you show us how you are injecting the enum at runtime? – dash Sep 10 '12 at 12:27
  • I pass it to a method via: (typof(class.MyEnumDefinition)) at compile time ;P – msfanboy Sep 12 '12 at 14:48

2 Answers2

0

The enum isn't really a member of the class, it's only declared in the scope of the class. You can use the GetNestedType method to get a type that is declared inside another. Example:

public class Demo {
  public enum Values { Apha, Beta }
}

Type t = typeof(Demo).GetNestedType("Values");
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
0

Well, you can try

(int)((reflectedType.GetEnumValues()
                    .Zip(reflectedType.GetEnumNames(), (v, n) => new { v, n })
                    .Where(p => p.n == FieldName)
                    .Single()).v)

This would give you the numeric value of your enum constant. You cannot however get the enum value, since this requires knowing the real enum type at compile-time.

Vlad
  • 35,022
  • 6
  • 77
  • 199