Parsing enumerations

Once in a while I need to convert an integer or text to some enum-value (usually when reading some settings from somewhere, where the actual value is limited int thus being represented by an enum …).

But I always keep forgetting how to do it … so now, here it is, once and for all:

// 1. option
RecipientTypeEnum rte = (RecipientTypeEnum) Enum.Parse(
typeof(RecipientTypeEnum),
1);
// 2. option
RecipientTypeEnum rte = (RecipientTypeEnum) Enum.Parse(
typeof(RecipientTypeEnum),
"To");

Both options will return a valid enum-value 🙂

Leave a Comment.