✅ 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:
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?
Thanks8 Replies
you can cast it to object and then to T
as T
should also work I thinkas 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!that boxes, no?
boxes?
I.e. it turns a value type in a reference type
Manually parse the string "0" or "1" to "false" or "true" before the logic happends?
Not the prettiest way, but it gets your fix
I think the boxing there gets optimized out
Thanks all - very helpful