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