Get Help:Ask a Question in our Forums|Report a Bug|More Help Resources
Last post Feb 13, 2013 12:40 AM by Paul Linton
Feb 01, 2013 04:00 PM|LINK
Who can help me to convert this to c #:
Function String2Enum(ByVal TypeEnum As System.Type, ByVal Name As String) As [Enum]
Return [Enum].GetValues(TypeEnum)(Array.IndexOf([Enum].GetNames(TypeEnum), Name))
NOTE: Automatic translators can not translate this code!
Feb 01, 2013 04:23 PM|LINK
I'm not the biggest fan of Visual Basic, but this may be what you are looking for :
public Enum String2Enum(Type TypeEnum, string Name)
return Enum.GetValues(TypeEnum)[Array.IndexOf(Enum.GetName(TypeEnum, Name))];
If you explain what you are trying to accomplish, there is likely a better method of handling this such as using Enum.GetName or one of the many built-in methods in the Enum Class :
Enum.GetName(Type yourEnumType, object yourVariable);
Check out this Stack Overflow discussion which may help you more than attempting to convert your current function.
Feb 12, 2013 11:31 PM|LINK
there is likely a better method of handling this such as using Enum.GetName or one of the many built-in methods in the Enum Class :
I think the one he's looking for is
Enum.Parse as it will take the string representation of the enum and return the enum value.
Enum.Parse(typeof(yourEnum), "yourEnumValueStringName", true);
Feb 13, 2013 12:23 AM|LINK
I don't think Rion's code will compile because Array.IndeOf needs two parameters. My stab at the answer is
Enum String2Enum(Type enumType, string name)
return Enum.Parse(enumType, name) as Enum;
Feb 13, 2013 12:34 AM|LINK
you must be funnin w/me ;)
String2Enum is a bit redundant when it seeks to replicate the built-in parse method...
Feb 13, 2013 12:40 AM|LINK
But if you don't know that Enum.Parse exists then you have to re-invent the wheel.
I suspect that a lot of code that is in production has redundent methods. A lot of framework methods would fall into the category of
"unknown unknowns" for people (me included).