3

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.

2
  • 1
    Can you add the compiler error to your question please. Commented Aug 23, 2019 at 8:16
  • What error you are getting? Commented Aug 23, 2019 at 8:17

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

6 Comments

That works. Can you explain why. Since Enum.TryParse<T> has the same where T: Enum constraint I would expect this to work and find this result very surprising.
@bikeman868 I've edited my answer. Enum.TryParse<T> has the constraint where T : struct, not where T : Enum see here
I did some reading, and to clarify: Enum is a class but a specific type of enum is a struct. So the Enum constraint constrains it to the Enum class or a class that inherits from Enum and the additional struct constraint means that it must also be a struct and only specific enum types have these characteristics.
@bikeman868 Yep, that's what my first paragraph tries to explain
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.