Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing IConvertible.GetTypeCode

Tags:

.net

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

like image 283
Josh Avatar asked Aug 17 '09 16:08

Josh


2 Answers

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.

like image 91
Reed Copsey Avatar answered Oct 23 '22 10:10

Reed Copsey


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.

like image 45
Scott Dorman Avatar answered Oct 23 '22 11:10

Scott Dorman