tags:

views:

208

answers:

2

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

A: 

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.

Scott Dorman
+1  A: 

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 effect 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.

Reed Copsey
Thanks, I've since checked Reflector too and found a couple of low-level methods that access it such as System.Variant.MarshalHelperConvertObjectToVariant. I guess the bottom line is that there's little to no reason for me to advertise it as a boolean so the best course of action appears to be to just return TypeCode.Object.
Josh Einstein
That's what I'd recommend, unless you have a strong reason not to do so. Setting it to Boolean may have unintended consequences.
Reed Copsey