Have you ever had a
Nullable<...> type which you needed to read to a regular value type, but needed a "default" value for when it was NULL, as the regular value type cannot handle it?Chances are, you've written it in one of the following ways:
int? i = null; // please note that Nullable<int> is the same as int?int a;if(i.HasValue) // equal to: if(i != null)  a = i.Value;else  a = -1;or
int a = i.HasValue ? i.Value : -1; // This is already a bit shorter!But using the NULL coalescing operator, you can simply write:
Which simply means: Read i's value, unless it is 
You can also use it in equations, like:
NULL, in which case you should use the value -1.You can also use it in equations, like:
int? a, b, c;a = null;b = 2;c = 1;int d = (a ?? 1) * ((b ?? 0) + (c ?? 0)); 
 
No comments :
Post a Comment