C# enum members at runtime

  • Thread starter Thread starter Ken Allen
  • Start date Start date
K

Ken Allen

I have a need to convert the names of the members of an enumeration into an
array of strings at runtime.

I have determined a method using reflection.

Type theType = typeof(MyEnumName);
MemberInfo[] theMembers = theType.getMembers();

foreach (MemberInfo entry in theMembers)
{
if ((entry.MemberType.ToString() == "Field") && (entry.Name !=
"value__))
{
// add this entry.Name to the list
}
}

Unfortunately this method means that I do not know how many members there
are in the enumeration until I have scanned the entire MemberInfo array.

Is there a simpler or more direct method for achieving this?

-ken
 
Ken Allen said:
I have a need to convert the names of the members of an enumeration
into an array of strings at runtime.

I have determined a method using reflection.

Type theType = typeof(MyEnumName);
MemberInfo[] theMembers = theType.getMembers();

foreach (MemberInfo entry in theMembers)
{
if ((entry.MemberType.ToString() == "Field") && (entry.Name !=
"value__))
{
// add this entry.Name to the list
}
}

Unfortunately this method means that I do not know how many members
there are in the enumeration until I have scanned the entire
MemberInfo array.

Is there a simpler or more direct method for achieving this?

Yup -

string[] names = Enum.GetNames(typeof(MyEnumName));
 
Cool.

Now, since this is a 'falg' (or bit field) enum, how can I get the value for
each of the names at the same time?

-ken

Jon Skeet said:
Ken Allen said:
I have a need to convert the names of the members of an enumeration
into an array of strings at runtime.

I have determined a method using reflection.

Type theType = typeof(MyEnumName);
MemberInfo[] theMembers = theType.getMembers();

foreach (MemberInfo entry in theMembers)
{
if ((entry.MemberType.ToString() == "Field") && (entry.Name !=
"value__))
{
// add this entry.Name to the list
}
}

Unfortunately this method means that I do not know how many members
there are in the enumeration until I have scanned the entire
MemberInfo array.

Is there a simpler or more direct method for achieving this?

Yup -

string[] names = Enum.GetNames(typeof(MyEnumName));
 
Ken Allen said:
Now, since this is a 'falg' (or bit field) enum, how can I get the value for
each of the names at the same time?

Well, there's Enum.GetValues as well, but I don't think there's any
guarantee that the order will be the same...
 
I was useing reflection to acheive the same results. I wanted to make the
values of an enumeration dynamically available to a user in a list box. In
order to do it I performed the following steps:

Type tEnum = typeof(DRW.Drawing2D.InterpolationMode);
Array aVals = Enum.GetValues(tEnum);

foreach(DRW.Drawing2D.InterpolationMode im in aVals)
{
String strName = im.ToString();
}

This worked for me.
 
Hi Brian,

Instead of getting all valies and convert them to strings you can use
Enum.GetNames method
 
Back
Top