Why are generic Parse methods for Enum types constrained with struct
rather than directly with Enum
itself?
#112776
-
Ref. Link: Why is the generic type parameter set as public static TEnum Parse<TEnum>(string value) where TEnum : struct; Rather it should have been defined as below: public static TEnum Parse<TEnum>(string value) where TEnum : Enum; Since the type constraint is defined as a struct, unable to cast the resulting value to an integer. I am attempting to create a generic method that returns a dictionary when Enum is provided as its input. I've constrained the generic type to be // Invocation - EnumNamedValues<DayOfWeek>();
public static IDictionary<int, string?> EnumNamedValues<T>() where T : Enum
{
var items = new Dictionary<int, string?>();
var enumType = typeof(T);
int item;
foreach (var name in Enum.GetNames(enumType))
{
//item = (int)Enum.Parse<T>(name); // Not working because of the incorrect type constraint of Parse method
item = (int)Enum.Parse(enumType, name);
if (items.ContainsKey(item))
{
items[item] += ", " + name;
}
else
{
items.Add(item, name);
}
}
return items;
} This is the error message when the generic Parse method is used, which is incorrect and error-prone as any struct value can be used here. Defeats the ultimate purpose of using generic constraints.
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 21 replies
-
The only good thing here is that the Parse method has a runtime validation that prevents it from using a type that is not an Enum. But when I update the generic type constraint of my method to be of // For any given enum, casting to type int should work. If Parse is successful, this should work.
var item = (int)Enum.Parse<T>(name); // Cannot convert type 'T' to 'int' |
Beta Was this translation helpful? Give feedback.
-
The correct constraint is Your caller method should also be constrained with |
Beta Was this translation helpful? Give feedback.
Yes, it was introduced before
Enum
can be used in constraint, so it can only usestruct
then.Changing from
struct
to the correctstruct, Enum
constraint is a breaking change.You can see methods introduced later (
GetValues
,GetNames
) are constrained withstruct, Enum
.Parse
just came too early.