I asked this question on Stack Overflow and it was met with negative reception. I figured that Stack Overflow wasn’t the right place to ask this question, so I decided to post it here.
Beside making types like SqlBoolean
act more naturally, is there any other reason? If making three state boolean types is the only purpose of this decision, is it a good enough reason to add a feature that is so rarely used to a language?
Here’s an example:
public class ThreeStateBool
{
private bool? value;
public ThreeStateBool(bool? value)
{
this.value = value;
}
public static bool operator false(ThreeStateBool tsb)
{
return tsb.value == false;
}
public static bool operator true(ThreeStateBool tsb)
{
return tsb.value == true;
}
}
Now that I’ve overloaded true
and false
, I can use this object in a conditional statement like:
if (new ThreeStateBool(false))
Console.WriteLine("false");
else if (new ThreeStateBool(true))
Console.WriteLine("true");
else if(new ThreeStateBool(null))
Console.WriteLine("null");
2
You have to have a bit of context here: I think the main point missing is that this was a pre C#2.0 feature, which means it’s a feature that came before nullable types. The page that describes the overloading of the ‘true’ operator is clearly geared towards the direction of having a nullable boolean without using a nullable type as support.
But there are other cases where you might want to treat an object instance as a boolean, for example where you want to check if the internal state of an object is ok, and you would want to write something C-style:
if (obj) {
obj.DoSomething();
}
It’s a possibility, it’s not a mandatory thing that you’d want to do. It’s a tool to be used if needed, and, as you well noted, it is somehow superseded by the use of nullable types; however, you might want to write something similar to a ThreeStateBoolean
when you know, for example, that ‘false’ means ‘null or false’. Writing those checks inline every time is a boring affair.
5