Overloading Operators in C# - Overloading true and false
(Page 4 of 4 )
The true and false operators are used in the extremely rare case of operators defining types with three-state logic to enable these types to work seamlessly with conditional statements and operators—namely, the if, do, while,for, and?:. TheSystem.Data.SqlTypes.SqlBooleanstruct provides this functionality. For example:
class Test
{
static void Main()
{
SqlBoolean a = SqlBoolean.Null;
if (a)
Console.WriteLine("True");
else if (! a)
Console.WriteLine("False");
else
Console.WriteLine("Null");
}
}
OUTPUT:
Null
The following code is a reimplementation of the parts ofSqlBooleannecessary to demonstrate thetrueandfalseoperators:
public struct SqlBoolean
{
public static bool operator true (SqlBoolean x)
{
return x.m_value == True.m_value;
}
public static bool operator false (SqlBoolean x)
{
return x.m_value == False.m_value;
}
public static SqlBoolean operator !(SqlBoolean x)
{
if (x.m_value == Null.m_value) return Null;
if (x.m_value == False.m_value) return True;
return False;
}
public static readonly SqlBoolean Null = new SqlBoolean(0);
public static readonly SqlBoolean False = new SqlBoolean(1);
public static readonly SqlBoolean True = new SqlBoolean(2);
private SqlBoolean (byte value) {m_value = value;}
private byte m_value;
}
Please check back next week for the continuation of this article.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |
|
This article is excerpted from chapter four of C# 3.0 in a Nutshell, Third Edition, A Desktop Quick Reference, written by Joseph Albahari and Ben Albahari (O'Reilly; ISBN: 0596527578). Check it out today at your favorite bookstore. Buy this book now.
|
|