Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible bug in C# 7.3 handling of generic Enum constraints [duplicate]

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.

like image 965
bikeman868 Avatar asked Dec 21 '25 04:12

bikeman868


1 Answers

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.

like image 141
canton7 Avatar answered Dec 23 '25 18:12

canton7