I have inherited a web api that has lots of enums defined in code, I want to convert them to a view-model class called EnumView so they can be serialized as below...
{Id: value, Name: enumName}
public class EnumView
{
public int Id { get; set; }
public string Name { get; set; }
}
Upon restricting the Generic class to the enum type, I get the warning
Constraint cannot be special class 'System.Enum'
This is the generic converter that I was 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;
}
}
Without T being constrained to an enum, the following conversion doesn't compile...
Id = (int)enumValue,
Due to the issue around a lack of generic enum constraints, what's the best way to go about this?
(int)enumValue
doesn't compile I guess.Because there's no guarantee thatenumValue
must be anint
. BTW,Enum
's are serializable too. – Amit Kumar Ghosh