Converting String to Enum Value

G

Guest

In a posting earlier this year I found a simple approach to convert a string
to a particular Enum value. The one line solution looked like this:

MyEnum ConvertedString = (MyEnum) Enum.Parse(typeof(MyEnum), MyString, true);

This is fine if one wants to hardcode each and every Enum in an If-ElseIf or
Select-Case construct but I'm wondering if there's a way to do it generically?

I have a situation where I'm using reflection to set a value. Here is the
code I've successfully been using:
propInfo.SetValue(node.Obj, Convert.ChangeType(newval,
propInfo.PropertyType, null), indexer);

This has worked perfectly for the basic user types (ex. string, bool, int,
etc.) but fails if I try to introduce a property that is defined with a type
of one of my Enums.

Any ideas?
 
D

Derrick

Just a shot in the dark here...

Since you have propInfo.PropertyType, which is a System.Type, you should be
able to check System.Type.IsEnum to see if the type in question is an
enumeration. Then, you may be able to parse based on that. Something to
the effect of (note: I didn't test this):

if(propInfo.PropertyType.IsEnum)
{
object val = Enum.Parse(propInfo.PropertyType, newVal);
propInfo.SetValue(node.Obj, val, indexer);
}
//Maybe need some else if's for different property types??
else
{
//your existing code:
propInfo.SetValue(node.Obj, Convert.ChangeType(newval,
propInfo.PropertyType, null), indexer);

}
 
G

Guest

Derrick,

Your shot in the dark was a good one! In addition to your change, I had to
enhance some code elsewhere but it was worth it. For now I am storing the
actual English enum values rather than their numeric equivalents. This
removes a layer of obfuscation, which will make troubleshooting and future
analysis much easier.

Thank you!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top