What is the purpose and effect of the true
and false
operators in C#? The official documentation on these is hopelessly non-explanatory.
views:
966answers:
5See the referenced example in the article
C# Language Specification -- Database boolean type
Essentially these operators allow an instance of a type to be used in boolean conditional logic such as &&
and ||
.
They allow you to overload them using the operator overloading syntax so that a type you define can be interpreted as a boolean.
The allow you to use a custom type as a part of logic operations; For example, as part of an if or while statement.
You would overload the true
or false
operators if you were defining a specialized boolean value. This is not typically needed, however, which is why they don't seem useful. For example, in a fuzzy-logic boolean class, you might have something like this:
// Represents a boolean that can store truth values in a range from [0, 1], with
// a value of one indicating complete metaphysical certitude and a value of
// zero indicating complete impossibility.
public class FuzzyBoolean {
// ...
public static bool operator true(FuzzyBoolean fb) {
return fb.TruthValue > 0;
}
public static bool operator false(FuzzyBoolean fb) {
return fb.TruthValue == 0;
}
// ...
}
Note that if you overload true
, you must also overload false
(and vice versa).
Of course, there are also the true
and false
literals, the two literal values you can assign to a boolean instance. Don't confuse these with the operators mentioned above. A more substantial example of how you'd use this, involving booleans in a database, is given in the MSDN docs here.
The true and false operators can be overloaded, to allow a class to represent its own state as true or false, for example:
public class MyClass
{
//...
public static bool operator true(MyClass op)
{
// Evaluation code...
}
public static bool operator false(MyClass op)
{
// Evaluation code...
}
}
And you will be able to use the operator in boolean expressions:
MyClass test = new MyClass(4, 3);
if (test)
Console.WriteLine("Something true");
else
Console.WriteLine("Something false");
string text = test ? "Returned true" : "Returned false";