Convert string to Enum c#

Converting a string to enum is quite easy one, but it need some attention when converting from string to enum. I will try to explain you how you can convert from a string to enum type. There is a method IsDefined i.e. Enum.IsDefined(typeof(AddressType), type) however this comparison does not incorporate string CASE options hence you may get undesirable results. It is best to use the CheckStringValueInEnum method below.

AddressType addresssType;
if (Formatter.CheckStringValueInEnum(type, AddressType)) {
	addresssType = (AddressType)Enum.Parse(typeof(AddressType), type, true);
} else {
	addresssType = AddressType.NA;

//used to check existence of string in enum
public static bool CheckStringValueInEnum(string stringValue, Enum e) {
	foreach (string enumString in Enum.GetNames(e.GetType()))
		if (string.Compare(enumString, stringValue, true) == 0)
			return true;
	return false;



comments powered by Disqus


Recent Tweets

@jeffrey_doucet @Brian_Bancroft Canadians, self define themselves as NOT American, rather than being Proud Canadians
Retweeted by @dyardy Why do so many Canadians obsess over American policy that won’t impact us while being fairly ambivalent to day-to-d……
@melrobbins I was looking for 50$ earlier today, and still can't find it...ideas :)
Trump Watches Up To 8 Hours Of TV Per Day | HuffPost #SmartNews ===that explains everything…
Retweeted by @dyardy Boston