public static T Convert<T>(String value) { return (T)Convert.ChangeType(value, typeof(T)); } public enum Category { Empty, Name, City, Country } Category cat=Convert<Category>("1");//Name=1
When I call Convert.ChangeType
, the system throws an exception on the impossibility of conversion from String to Category. How to do the conversion? Maybe I need to implement any converter for my type?
1 Enum to string. To convert enum to string use simply Enum.ToString method. Animal animal = Animal .Cat; string str = animal. 2 String to enum. To convert string to enum use static method Enum.Parse . Parameters of this method are enum type, the string value and optionally indicator to ignore case. 3 See also
The ChangeType (Object, Type) method can convert an enumeration value to another type. However, it cannot convert another type to an enumeration value, even if the source type is the underlying type of the enumeration.
Use the Enum.ToObject () method to convert integers to enum members, as shown below. Example: Convert int to Enum using Enum.ToObject () int i = 2, j = 6, k = 10; Week day1, day2, day3; day1 = (Week)Enum.ToObject(typeof(Week), i); day2 = (Week)Enum.ToObject(typeof(Week), j); day3 = (Week)Enum.ToObject(typeof(Week), k);
It is best practice to use the TryParse () method that does not raise exceptions. The following example shows the conversion of string to enum using TryParse<TEnum> () method in .NET 4.x and .NET 5: In the above example, Enum.TryParse () converts the three different strings to enum members.
Use Enum.Parse method for this.
public static T Convert<T>(String value) { if (typeof(T).IsEnum) return (T)Enum.Parse(typeof(T), value); return (T)Convert.ChangeType(value, typeof(T)); }
.Net Core version :
public static T Convert<T>(string value) { if (typeof(T).GetTypeInfo().IsEnum) return (T)Enum.Parse(typeof(T), value); return (T)System.Convert.ChangeType(value, typeof(T)); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With