Mog0
Mog0

Reputation: 2087

Enum.TryParse not accepted in generic restricted to Enum

I think I'm probably doing something silly but I'm trying to write a generic function that takes a string and converts it into an enum (and then does some other stuff that I've skipped for sake of brevity). The problem is, it complains that Enum.TryParse needs a type that isn't nullable, it complains that T is nullable; Seemingly System.Enum is nullable but actual enums aren't nullable. Is there something I'm doing wrong here or is there a way around the problem.

private T GetEnumFilter<T>(string strValue) where T : Enum
{
     return Enum.TryParse(strValue, out T value) ? value : throw new Exception("Invalid value");
}

I've seen this https://stackoverflow.com/a/8086788/1093406 answer and the sample at the dotnet samples and can't see what I've done wrong.

Upvotes: 3

Views: 952

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500535

Seemingly System.Enum is nullable but actual enums aren't nullable.

Yes, just like System.ValueType is a reference type, but value types themselves aren't.

You just need to add a struct constraint:

private T GetEnumFilter<T>(string value) where T : struct, Enum

This compiles, for example:

private static T GetEnumFilter<T>(string value) where T : struct, Enum =>
    Enum.TryParse(value, out T result) ? result : throw new Exception("Invalid value");

Upvotes: 7

Related Questions