The following code does not compile in C# 7.3 even though it does support generics constrained to be enums:
using System;
public class Test<T> where T: Enum
{
public void Method()
{
if (!Enum.TryParse<T>("something", out var value))
throw new Exception("Oops");
}
}
My other code that uses Enum constraints does work, so I have the right versions of everything, it just doesn't seem to be able to call another method that also is constrained to be an Enum.
Is this a bug or did I misunderstand how this is is supposed to work.
You need an extra constraint:
public class Test<T> where T: struct, Enum
{
public void Method()
{
if (!Enum.TryParse<T>("something", out var value))
throw new Exception("Oops");
}
}
With just where T : Enum, you're allowed to call new Test<Enum>().Method(); -- i.e. pass in the Enum type, rather than any specific type of enum. Adding struct means you have to pass in a specific type of enum.
More specifically, Enum.TryParse<T> has the constraint where T : struct, so you need to match this constraint in your method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With