Saturday, August 11, 2018

.net - Cannot define T in C#





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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...