C#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;
    }
}


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
Was this page helpful?