Prev | Current Page 253 | Next

Jon Skeet

"C# in Depth: What you need to master C# 2 and 3"

Now let??™s consider the operators, where things are
slightly more tricky.
OPERATORS INVOLVING NULLABLE TYPES
C# allows the following operators to be overloaded:
?–  Unary: + ++ - -- ! ~ true false
?–  Binary: + - * / % & | ^ << >>
?–  Equality:4 == !=
?–  Relational: < > <= >=
When these operators are overloaded for a non-nullable value type T, the nullable type
T? has the same operators, with slightly different operand and result types. These are
called lifted operators whether they??™re predefined operators like addition on numeric
types, or user-defined operators like adding a TimeSpan to a DateTime. There are a few
restrictions as to when they apply:
?–  The true and false operators are never lifted. They??™re incredibly rare in the
first place, though, so it??™s no great loss.
?–  Only operators with non-nullable value types for the operands are lifted.
?–  For the unary and binary operators (other than equality and relational operators),
the return type has to be a non-nullable value type.
?–  For the equality and relational operators, the return type has to be bool.
?–  The & and | operators on bool? have separately defined behavior, which we??™ll
see in section 4.3.6.
For all the operators, the operand types become their nullable equivalents. For the
unary and binary operators, the return type also becomes nullable, and a null value is
returned if any of the operands is a null value.


Pages:
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265