3

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.

3
  • 1
    You shouldn't shadow your argument name with a variable name. Use some different name for out T value and ? value : Commented Nov 11, 2020 at 17:12
  • @ckuri: there's already answer suggesting that Commented Nov 11, 2020 at 17:16
  • Sorry, made a couple of errors when simplifying my code for SO. Thanks to @HereticMonkey for pointing out the mistake Commented Nov 11, 2020 at 17:20

1 Answer 1

7

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");
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Jon for the amazingly fast answer. I've fixed the code errors in my question introduced when simplifying for SO but the super simple addition of struct is what I was missing.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.