Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert.ChangeType How to convert from String to Enum

  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?

like image 366
Mixer Avatar asked Dec 30 '13 08:12

Mixer


People also ask

How to convert enum to string in C++?

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

Can the changetype method convert an enumeration to another type?

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.

How to convert integers to enum members in Java?

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);

How to convert string to enum using TryParse() method?

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.


2 Answers

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)); } 
like image 52
Tony Avatar answered Sep 21 '22 09:09

Tony


.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)); } 
like image 38
trenoncourt Avatar answered Sep 22 '22 09:09

trenoncourt