I’m a little unclear on when/if the Value property on nullable types must be used when getting the value contained in a nullable type. Consider the following example:
int? x = 10;
Console.WriteLine("The value of 'x' is " + x.Value);
Console.WriteLine("The value of 'x' is " + x);
Both of these return the same value (10).
However, if I initially set x to null, the first Console.WriteLine throws an exception and the second one does not.
So, my question is this. What is the point of using the Value property? It doesn’t appear to be needed to get the actual value (even if it’s null) and will throw an exception if the value is indeed null.
It is needed usually – just not in your particular case. The type of
xisNullable<int>, notint– and there’s no implicit conversion fromNullable<T>toT.Let’s look at what’s happening in your example though. Your final line is being converted into:
That’s boxing
x, which will result in either a boxedintor a null reference… both of which are handled bystring.Concat.When you’re not converting to a string via string concatenation, e.g. if you wanted:
then you do have to use the
Valueproperty – or an explicit cast, or possibly a null coalescing operator, or a call toGetValueOrDefault: