Prev | Current Page 246 | Next

Jon Skeet

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


It??™s a shorthand way of using a nullable type, so instead of using Nullable
we can use byte? throughout our code. The two are interchangeable and compile to
exactly the same IL, so you can mix and match them if you want to, but on behalf of
whoever reads your code next, I??™d urge you to pick one way or the other and use it
consistently. Listing 4.3 is exactly equivalent to listing 4.2 but uses the ? modifier.
int? nullable = 5;
object boxed = nullable;
Console.WriteLine(boxed.GetType());
int normal = (int)boxed;
Console.WriteLine(normal);
nullable = (int?)boxed;
Console.WriteLine(nullable);
nullable = new int?();
boxed = nullable;
Console.WriteLine (boxed==null);
nullable = (int?)boxed;
Console.WriteLine(nullable.HasValue);
I won??™t go through what the code does or how it does it, because the result is exactly the
same as listing 4.2. The two listings compile down to the same IL??”they??™re just using different
syntax, just as using int is interchangeable with System.Int32. The only changes
are the ones in bold. You can use the shorthand version everywhere, including in
method signatures, typeof expressions, casts, and the like.
The reason I feel the modifier is very well chosen is that it adds an air of uncertainty
to the nature of the variable. Does the variable nullable in listing 4.3 have an
integer value? Well, at any particular time it might, or it might be the null value.


Pages:
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258