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?
IConvertible.GetTypeCode on MSDN
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.
Based on the description for TypeCode.Boolean it represents "A simple type representing Boolean values of true or false." This sounds like it fits with the description of your struct since you said that it only contains a Boolean value and is implicitly convertible between them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With