C# 7.3 'Enum' generic constraint should be sufficient for calls to Enum.TryParse
The following code fails with _CS0453: The type 'TEnum' must be a non-nullable value type in order to use it as parameter 'TEnum' in the generic type or method 'Enum.TryParse
c#
public TEnum Parse<TEnum>(string value) where TEnum : Enum
{
return Enum.TryParse<TEnum>(value, out var result)
? result
: default;
}
Roslyn (C# compiler) issue? https://github.com/dotnet/roslyn
Changing the constraint from struct to Enum would be a source breaking change. This would no longer compile:
public static T ParseHelper<T>(string s) where T : struct
{
if (typeof(T).IsEnum))
return Enum.TryParse<T>(...);
else
...
}
Also, the : Enum constraint doesn't give you the strict semantic one would want because it still lets you do:
static void Check<T>() where T : Enum { }
// This compiles just fine, even though System.Enum is not an enum
Check<System.Enum>();
where T : Enum should probably imply struct though; which is why I'm suggesting its a compiler rather than an api issue
where T : Enumshould probably implystructthough; which is why I'm suggesting its a compiler rather than an api issue
That can't be expressed in the file format. The only thing that can be expressed in the file format is "is or derives from this type", which is why C# still forbids where T : ValueType (because System.ValueType meets the constraint too, but System.ValueType is a reference type, same as System.Enum, and it doesn't do what one would expect it to do).
We would have to do a file format change to make it work as expected (includes updates to the runtimes and tools). Changing what where T : Enum does would now be breaking, so I don't think Roslyn is going to ever revisit this.
Ah, I see what you mean - they should secretly make where T : Enum into where T : struct, Enum. Might be worth an issue in Roslyn, but that ship probably sailed.