Prev | Current Page 252 | Next

Jon Skeet

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

We??™ll start with the
conversions, and then look at operators.
CONVERSIONS INVOLVING NULLABLE TYPES
For completeness, let??™s start with the conversions we already know about:
?–  An implicit conversion from the null literal to T?
?–  An implicit conversion from T to T?
?–  An explicit conversion from T? to T
Now consider the predefined and user-defined conversions available on types. For
instance, there is a predefined conversion from int to long. For any conversion like
this, from one non-nullable value type (S) to another (T), the following conversions
are also available:
?–  S? to T? (explicit or implicit depending on original conversion)
?–  S to T? (explicit or implicit depending on original conversion)
?–  S? to T (always explicit)
To carry our example forward, this means that you can convert implicitly from int? to
long? and from int to long? as well as explicitly from long? to int. The conversions
behave in the natural way, with null values of S? converting to null values of T?, and
non-null values using the original conversion. As before, the explicit conversion from
S? to T will throw an InvalidOperationException when converting from a null value
of S?. For user-defined conversions, these extra conversions involving nullable types
are known as lifted conversions.
125 C# 2??™s syntactic sugar for nullable types
So far, so relatively simple.


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