Randy Minder Randy Minder - 1 month ago 10x
C# Question

C# Nullable Types and the Value property

I'm a little unclear on when/if the

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
, the first
throws an exception and the second one does not.

So, my question is this. What is the point of using the
property? It doesn't appear to be needed to get the actual value (even if it's
) and will throw an exception if the value is indeed


It is needed usually - just not in your particular case. The type of x is Nullable<int>, not int - and there's no implicit conversion from Nullable<T> to T.

Let's look at what's happening in your example though. Your final line is being converted into:

Console.WriteLine(string.Concat("The value of 'x' is ", x));

That's boxing x, which will result in either a boxed int or a null reference... both of which are handled by string.Concat.

When you're not converting to a string via string concatenation, e.g. if you wanted:

int nonNullable = x.Value;

then you do have to use the Value property - or an explicit cast, or possibly a null coalescing operator, or a call to GetValueOrDefault:

int nonNullable = (int) x;
int alternative = x ?? 20;
int andAnother = x.GetValueOrDefault(20);