Any clue how to define T in this code?
public static T ToEnum(this string value, T defaultValue)
{
if (string.IsNullOrEmpty(value))
{
return defaultValue;
}
T result;
return Enum.TryParse(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)'
Answer
Try using a constraint
to have a value type which is a struct
, for sample:
public static T ToEnum(this string value, T defaultValue)
where T : struct
{
if (string.IsNullOrEmpty(value))
{
return defaultValue;
}
T result;
return Enum.TryParse(value, true, out result) ? result : defaultValue;
}
I haven't tested it.
No comments:
Post a Comment