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

19 Types of Developers Explained…
Can't Afford Photoshop? Here Is The Best Free Drawing Software | Digital Trends…
Retweeted by @dyardy Fun day christening Amazon’s latest wind farm. #RenewableEnergy
Retweeted by @dyardy Hey C# peeps, we’re trying C# in browser with reference content. Try it here:… reply with feedback /cc @LadyNaggaga
23 Amazing Vintage Photographs Taken Inside WWII Tank Factories ~ vintage everyday…