Reflection: how to get numeric values from an enum?

Reflection: how to get numeric values from an enum?

Post by Ted Mille » Sat, 11 Oct 2003 09:53:53


Using reflection to parse the type info in an assembly. For enums, how to
get the constant values for the members? The FieldInfo.Value field has the
symbolic value, not the constant value. There's a HasDefault attribute but
no mention I can find about *where* the default value is actually stored.

enum Color {
Red = 1,
Green = 2,
Blue = 3
};

***

static private void ParseEnum(System.Type objType) {

FieldInfo[] arrObjFields = objType.GetFields();

foreach(FieldInfo objField in arrObjFields) {
Console.WriteLine("\t" + objField.Name + " " +
objField.GetValue(objField).ToString());
}
}

results in something like

enum Color {
Red = Red
Green = Green
Blue = Blue
};

Arg! What am I doing wrong?
 
 
 

Reflection: how to get numeric values from an enum?

Post by Mattias Sj » Sat, 11 Oct 2003 23:12:12

Ted,


The default behavior for Enum.ToString() is to return the name string,
not the value. Change it to .ToString("d") to print the integer value
instead.



Mattias

--
Mattias Sjren [MVP] mattias @ mvps.org
http://www.yqcomputer.com/
Please reply only to the newsgroup.

 
 
 

Reflection: how to get numeric values from an enum?

Post by Ted Mille » Sun, 12 Oct 2003 07:39:43

Well, this lloked promising, but I don't see how to use this advice. I have
a Type object for the enum, from which I have retrieved an array of
FieldInfo objects. I cannot pass "d" to any of the available ToString
methods.

I must be missing something more basic.

--
 
 
 

Reflection: how to get numeric values from an enum?

Post by Ted Mille » Sun, 12 Oct 2003 08:08:40

Well, your reply spurred me to examine what I was doing, and did help. I was
overcomplicating things. The Enum type has a bunch of static methods that do
exactly what I want.

foreach(object obj in Enum.GetValues(objType)) {
Console.WriteLine("{0} =
{1}",obj.ToString(),Enum.Format(objType,obj,"d"));
}

--
 
 
 

Reflection: how to get numeric values from an enum?

Post by Girish Bha » Wed, 15 Oct 2003 00:37:19

If you know that the value of the enum is going to be an int,you probably
can use Convert.ToInt32() on that GetValue. Here is what I found.
1. You need to probably create an object of the type passed in.
2. You need to pass that object you just created to the GetValue() of
FieldInfo object. (So that it can do the lookup).
3. Convert.ToInt32() on the resulting object. This should work since the
object returned through GetValue() will be an Enum and that implements
IConvertible.


HTH

--
Girish Bharadwaj


have