Skip to main content
added 14 characters in body
Source Link
uluorta
  • 153
  • 1
  • 8

If it's ok to castuse direct casting afterwards, I guess you can use the System.Enum base class in your method, wherever necessary. You just need to replace the type parameters carefully. So the method implementation would be like:

public static class EnumUtils { public static Enum GetEnumFromString(string value, Enum defaultValue) { if (string.IsNullOrEmpty(value)) return defaultValue; foreach (Enum item in Enum.GetValues(defaultValue.GetType())) { if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item; } return defaultValue; } } 

Then you can use it like:

var parsedOutput = (YourEnum)EnumUtils.GetEnumFromString(someString, YourEnum.DefaultValue); 

If it's ok to cast afterwards, I guess you can use the System.Enum base class in your method, wherever necessary. You just need to replace the type parameters carefully. So the method implementation would be like:

public static class EnumUtils { public static Enum GetEnumFromString(string value, Enum defaultValue) { if (string.IsNullOrEmpty(value)) return defaultValue; foreach (Enum item in Enum.GetValues(defaultValue.GetType())) { if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item; } return defaultValue; } } 

Then you can use it like:

var parsedOutput = (YourEnum)EnumUtils.GetEnumFromString(someString, YourEnum.DefaultValue); 

If it's ok to use direct casting afterwards, I guess you can use the System.Enum base class in your method, wherever necessary. You just need to replace the type parameters carefully. So the method implementation would be like:

public static class EnumUtils { public static Enum GetEnumFromString(string value, Enum defaultValue) { if (string.IsNullOrEmpty(value)) return defaultValue; foreach (Enum item in Enum.GetValues(defaultValue.GetType())) { if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item; } return defaultValue; } } 

Then you can use it like:

var parsedOutput = (YourEnum)EnumUtils.GetEnumFromString(someString, YourEnum.DefaultValue); 
Source Link
uluorta
  • 153
  • 1
  • 8

If it's ok to cast afterwards, I guess you can use the System.Enum base class in your method, wherever necessary. You just need to replace the type parameters carefully. So the method implementation would be like:

public static class EnumUtils { public static Enum GetEnumFromString(string value, Enum defaultValue) { if (string.IsNullOrEmpty(value)) return defaultValue; foreach (Enum item in Enum.GetValues(defaultValue.GetType())) { if (item.ToString().ToLower().Equals(value.Trim().ToLower())) return item; } return defaultValue; } } 

Then you can use it like:

var parsedOutput = (YourEnum)EnumUtils.GetEnumFromString(someString, YourEnum.DefaultValue);