Iterators and Nullable Types - Mixing nullable and nonnullable operators
(Page 4 of 4 )
You can mix and match nullable and nonnullable types (this works because there is an implicit conversion from T to T?):
T to T? ):You can mix and match nullable and nonnullable types (this works because there is an implicit conversion from T to T?):
int? x = null;
int y = 2;
int? z = x + y; // equivalent to x + (int?)y
// z is null
bool?
When supplied operands of type bool?, the & and | operators treat null as an unknown value. So,null | trueis true, because:
If the unknown value is false, the result would be true.
- If the unknown value is true, the result would be true.
Similarly,null & falseis false. This behavior would be familiar to SQL users. The following example enumerates other combinations:
bool? n = null;
bool? f = false;
bool? t = true;
Console.WriteLine (n | n); // (null)
Console.WriteLine (n | f); // (null)
Console.WriteLine (n | t); // True
Console.WriteLine (n & n); // (null)
Console.WriteLine (n & f); // False
Console.WriteLine (n & t); // (null)
Null Coalescing Operator
The ?? operator is the null coalescing operator, and it can be used with both nullable types and reference types. It says “If the operand is nonnull, give it to me; otherwise, give me a default value.” For example:
int? x = null;
int y = x ?? 5; // y is 5
The?? operator is equivalent to callingGetValueOrDefaultwith an explicit default 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.
|
|