Reputation: 2498
I have a function with generic return type. If value parameter is a valid enum value, the method returns the related enum value.
How can I return the related enum value? Compiler error: Cannot convert type 'int?' to 'T'
public static T? GetEnumValue<T>(int? value)
{
if (value == null)
{
return null;
}
try
{
var enumValues = Enum.GetValues(typeof(T));
foreach (object enumValue in enumValues)
{
if (Convert.ToInt32(enumValue).Equals(value))
{
// ERROR: Cannot convert type 'int?' to 'T'
return (T)value;
}
}
}
catch (ArgumentNullException)
{
}
catch (ArgumentException)
{
}
catch
{
}
return null;
}
Thanks,
Upvotes: 1
Views: 483
Reputation: 1475
Three changes made it work for me. Changed return type to Nullabel and added where T : struct (nipped from https://stackoverflow.com/a/209219/455904) and changed the return in the middle to return enumValue.
public static Nullable<T> GetEnumValue<T>(int? value)
where T : struct
{
if (value == null)
{
return null;
}
try
{
var enumValues = Enum.GetValues(typeof(T));
foreach (object enumValue in enumValues)
{
if (Convert.ToInt32(enumValue).Equals(value))
{
return (T)enumValue;
}
}
}
catch (ArgumentNullException)
{
}
catch (ArgumentException)
{
}
catch
{
}
return null;
}
Upvotes: 1