I have inherited a web api that has many enumerations defined in the code, I want to convert them to a view model class called EnumView so that they can be serialized as shown below ...
{Id: value, Name: enumName}
public class EnumView
{
public int Id { get; set; }
public string Name { get; set; }
}
After restricting the Generic class to an enum type, I get a warning
The restriction cannot be a special class "System.Enum"
This is a generic converter that I am going to use ...
public class EnumViewConverter<T> where T : Enum
{
public static List<EnumView> ConvertToView()
{
List<EnumView> enumViews = new List<EnumView>();
T[] enumValues = (T[])Enum.GetValues(typeof(T));
foreach (var enumValue in enumValues)
{
var enumView = new EnumView
{
Id = (int)enumValue,
Name = Enum.GetName(typeof(T), enumValue)
};
enumViews.Add(enumView);
}
return enumViews;
}
}
If T is not limited to enumeration, the following conversion does not compile ...
Id = (int) enumValue,
Due to the lack of general enumeration restrictions, what is the best way to do this?
source
share