I was trying understand a extension method to convert string
to Enum
found here.
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;
}
Compile Error:
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)'
One the Comments says to add where T : struct
for the extension method to work.
Method With Constraint:
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 read the docs on Enum.TryParse , but I don't understand in docs on why where T : struct
is added as constraint for type T ?
Why would above extension wont work without constraint as struct
why not other value types ? How to relate struct
and Enum
type ? or Is it just a syntax to follow ?
Update:
Most of them said any value type can be used , I tried to use where T : int
But I get compile time error:
'int' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter.