© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•4y ago•
11 replies
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;
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
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

❔ generic class in generic method
C#CC# / help
3y ago
without generic class can i create generic method or generic field?
C#CC# / help
4y ago
Converting from a string to a generic method invocation
C#CC# / help
3y ago
Forwarding T to other generic method
C#CC# / help
3y ago