Converting String to User Defined Type

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I am trying to convert the value of a string to a defined enum value such as
follows.

public enum MyEnum { One, Two };

string MyString = "One";
// or even this is fine
string MyString2 = "MyEnum.One";

// This doesn't work (obviously), but effectively this
// is what I am trying to accomplish.
MyEnum ConvertedString = (MyEnum)MyString;

Is there a way using the TYPE object or reflection to accomplish this goal?
I am a pretty advanced developer and understand most topics and commands,
so feel free to offer any ideas.

I know the example is silly and why would anyone do this, but
I am really trying to read these enum values from a text file and
assign them to a variable within a class I have, but it would have
clouded the question if I showed all of that code.
I hope the simple example is enough?

Thanks for any help.

Greg
 
string MyString = "One";

MyEnum ConvertedString = (MyEnum)Enum.Parse(typeof(MyEnum), MyString, true);
 
Thank you so much. I don't know why I didn't even look for that when I knew
that Int32.Parse existed.
 
Simon (et al),

I like your approach:
MyEnum ConvertedString = (MyEnum)Enum.Parse(typeof(MyEnum), MyString, true);

But is there a way to make such a conversion if I can't explicitly
(hard-code) the Enum type into the statement?

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?
 
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);

}
 
Back
Top