Overloading Operators in C#
(Page 1 of 4 )
In this seventh part of a ten-part series on C#, you will learn how and why to overload operators, and more. 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). Copyright © 2007 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.
Scenarios for Nullable Types
One of the most common scenarios for nullable types is to represent unknown values. This frequently occurs in database programming, where a class is mapped to a table with nullable columns. If these columns are strings (e.g., an Email-Address column on a Customer table), there is not a problem as string is a reference type in the CLR, which can be null. However, most other SQL column types map to CLR struct types, making nullable types very useful when mapping SQL to the CLR. For example:
// maps to a Customer table in a database
public class Customer
{
...
public decimal? AccountBalance;
}
A nullable type can also be used to represent the backing field of an ambient property. An ambient property, if null, returns the value of its parent. For example:
public class Row
{
...
Grid parent;
Color? backColor;
public Color BackColor
{
get { return backColor ?? parent.BackColor; }
set { backColor = backColor == parent.BackColor ? null : value; }
}
}
Alternatives to Nullable Types
Before nullable types were part of the C# language (i.e., before C# 2.0), there were many strategies to deal with nullable value types, examples of which still appear in the .NET Framework for historical reasons. One of these strategies is to designate a particular nonnull value as the “null value”; an example is in the string and array classes. String.IndexOf returns the magic value of -1 when the character is not found:
int i = "Pink".IndexOf ('b');
onsole.WriteLine(s); // outputs -1
However,Array.IndexOfreturns-1only if the index is 0-bounded. The more general formula is thatIndexOfreturns 1 less than the minimum bound of the array. In the next example,IndexOfreturns0when an element is not found:
// Create an array whose lower bound is 1 instead of 0:
Array a = Array.CreateInstance (typeof(string),
new int[] {2}, new int[] {1});
a.SetValue("a", 1);
a.SetValue("b", 2);
Console.WriteLine(Array.IndexOf(a, "c")); // outputs 0
Nominating a “magic value” is problematic for several reasons:
It means that each value type has a different representation of null. In contrast, nullable types provide one common pattern that works for all value types.
There may be no reasonable designated value. In the previous example, –1 could not always be used. The same is true for our earlier examples representing an unknown account balance and an unknown temperature.
Forgetting to test for the magic value results in an incorrect value that may go unnoticed until later in execution—when it pulls an unintended magic trick. Forgetting to testHasValueon a null value, however, throws anInvalidOperationExceptionon the spot.
The ability for a value to be null is not captured in the type. Types communicate the intention of a program, allow the compiler to check for correctness, and enable a consistent set of rules enforced by the compiler.
Next: Operator Overloading >>
More C# Articles
More By O'Reilly Media
|
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.
|
|