C
C#3y ago
Hugh

✅ Specialising a generic method

I've got a generic method that takes a string and uses a TypeConverter to convert it to a specific type. However, when the requested type is bool, I want 0 and 1 to convert to false and true. I was hoping that I'd be able to do this:
private static T? Convert<T>(string input)
{
if(typeof(T) == typeof(bool))
{
return Convert<int>(input) != 0;
}

try
{
TypeConverter converter = TypeDescriptor.GetConverter(typeof(T));
return (T?)converter.ConvertFromString(input);
}
catch(NotSupportedException)
{
return default;
}
}
private static T? Convert<T>(string input)
{
if(typeof(T) == typeof(bool))
{
return Convert<int>(input) != 0;
}

try
{
TypeConverter converter = TypeDescriptor.GetConverter(typeof(T));
return (T?)converter.ConvertFromString(input);
}
catch(NotSupportedException)
{
return default;
}
}
However, I get an error on return Convert<int>(input) != 0; as it says "Cannot implicitly convert type 'bool' to 'T'", even though in this case the if statement has ensured that T is bool. How can I get this to work, either by convincing the compiler that T is bool in that situation, or any other way? Thanks
8 Replies
Anton
Anton3y ago
you can cast it to object and then to T as T should also work I think
Hugh
HughOP3y ago
as T says: "[CS0413] The type parameter 'T' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint" Casting to object then to T seems to work well, though - thanks!
ero
ero3y ago
that boxes, no?
Hugh
HughOP3y ago
boxes?
Thinker
Thinker3y ago
I.e. it turns a value type in a reference type
FusedQyou
FusedQyou3y ago
Manually parse the string "0" or "1" to "false" or "true" before the logic happends? Not the prettiest way, but it gets your fix
Anton
Anton3y ago
I think the boxing there gets optimized out
Hugh
HughOP3y ago
Thanks all - very helpful

Did you find this page helpful?