Saturday, 11 August 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...