-4

Any clue how to define T in this code?

 public static T ToEnum<T>(this string value, T defaultValue) { if (string.IsNullOrEmpty(value)) { return defaultValue; } T result; return Enum.TryParse<T>(value, true, out result) ? result : defaultValue; } 

Severity Code Description Project File Line Error CS0453 The type 'T' must be a non-nullable value type in order to use it as parameter 'TEnum' in the generic type or method 'Enum.TryParse(string, bool, out TEnum)'

2
  • @PetSerAl Please write out the whole code like an answer. Thank you! Commented Jan 15, 2016 at 18:40
  • 1
    Please read How to Ask. If you can define "this", you can search for it. Do you want a "generic type constraint for an enum"? Commented Jan 15, 2016 at 18:43

1 Answer 1

4

Try using a constraint to have a value type which is a struct, for sample:

public static T ToEnum<T>(this string value, T defaultValue) where T : struct { if (string.IsNullOrEmpty(value)) { return defaultValue; } T result; return Enum.TryParse<T>(value, true, out result) ? result : defaultValue; } 

I haven't tested it.

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

5 Comments

Beat me by a second!
It gives the error Severity Code Description Project File Line Error CS0451 The 'new()' constraint cannot be used with the 'struct' constraint
Try using the ´Enum` as a constraint!
Just remove , new() OP, an enum cannot be "new"
where T : Enum is not a valid template constraint in C#.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.