开发者

C# Nullable Types and the Value property

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 usin开发者_高级运维g 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 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);


x and x.Value have different types.

    static void Meth(int i)
    {
        int? x = 5;
        Meth(x);
        Meth(x.Value);
    }

Second line doesn't compile.

So reason of using x.Value is obvious - you need to call it when you need the actual value. And NullReferenceException is reasonable, because null doen't correspond to value of value type.


You should access Value property if HasValue property returns true, otherwise you will get an exception. Your example works because Nullable has overloaded ToString() method and C# compiler supports shortcuts for this type.


when x is null x.Value will throw a System.InvalidOperationException exception (no matter what is the type of x)

string + null = string : no exception


If you want to use .value for a nullable int. you can check the value like this

int? x = null;
int valXX = x.HasValue ? x.Value : 0;
Console.WriteLine("The value of 'x' is ->" + x + "<-");
Console.WriteLine("The value of 'valXX' is ->" + valXX + "<-");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜