blah blah blah is here! blah blah » Close

up2down
link

If I have an enumeration like:

public enum UserType

{
Anonymous = 1,
Registered = 2,
Pro = 3

}


And say I have a string:

string myType = "Registered";

Would it be possible to take the value of the string and cast it to a UserType?

last answered 2 years ago

1 answers

link

string myType = "Registered";

UserType userType = UserType.Anonymous; // default value
if(Enum.IsDefined(typeof(UserType), myType)) { // important to always check
userType = (UserType)Enum.Parse(typeof(UserType), myType);
}


EDIT
I'd post this as a comment to your original comment, but it doesn't have formatting so it looks ugly.

~~~

It's not just about preventing parse errors, but you can accidentially (or intentionally) parse a number which has nothing to do with your enumeration.

UserType ut = (UserType)Enum.Parse(typeof(UserType), "45");


is a valid parse, will not through an exception, and ut will carry a numeric value of 45 (instead of one of your 3 defined values), but if you pass that through the is defined method, it will return false and will prevent the parse from taking place.

you can also pass in multiple values (like a combined enum value):

UserType regPro = (UserType)Enum.Parse(typeof(UserType), "Registered, Pro");


is the same as:

UserType regPro = UserType.Registered | UserType.Pro;

Rick_A
761

+1 for the tip on checking if it is defined, cleaner than doing a try/catch.

Feedback