I’m nitpicking, I know. But when implementing the IConvertible interface on a structure that contains only a boolean value (and thus has only two states) what is the recommended value to return from IConvertible.GetTypeCode()? The structure is implicitly convertible and comparable to boolean and in nearly every aspect other than string and XML representation, it’s effectively a boolean.
I feel like I’m lying to the framework if I return TypeCode.Boolean but TypeCode.Object seems unnecessarily vague. Are there any real-world consequences for implementing this method in your own structures?
You can do this – but be wary.
Many routines use GetTypeCode directly, and this may have an impact if your struct is passed to one of them. If you override GetTypeCode to return TypeCode.Boolean, these routines will assume your struct is a bool, which may or may not have odd side effects.
In practice, most of the samples (such as VB’s IsNumeric routine) check for numeric types, so a bool TypeCode probably won’t affect this, but there are other cases where it may have an effect. Some ORMs, for example, check the type code to handle saving and loading of a type. If you want your struct to fool the world into thinking it’s a bool, that may help make it less obvious that your type isn’t actually a Boolean… but it may cause subtle issues, as well.