C# Nullable – Difference Between Casting and Calling .Value

ccoding-stylenet

Let's suppose we have a nullable variable.

int? myVar = null;

If we wish to use it's value, there are at least two options:

Explicit casting

DoSomething((int)myVar);

Calling Nullable<T>'s .Value property

DoSomething(myVar.Value);

I've noticed that when the conversion fails, in both cases the same exception is thrown (System.InvalidOperationException: Nullable object must have a value), which makes me think that they are both implemented in the same way (but I have found not evidence for that claim).

My question is:

  • Is there any difference between these two options? (i.e., is there some scenario where they would have a different behavior?)
  • Style-wise, is one of these two options preferred over the other? Why? According to which style guide?

Update:

It might be obvious, but just in case you stumble into this question, you might consider that an advantage of .Value versus explicit casting is that it prevents from unintendedly trying to cast to an incorrect type.

On the other hand, explicit casting might be easier to read in some scenarios. For instance, having var value = (int)myVar; allows an easier identification of the type than var value = myVar.Value;

Best Answer

If you check out the source for Nullable<T>, you'll see that the explicit cast operator does this:

public static explicit operator T(Nullable<T> value) {
    return value.Value;
}

And that that Value property does:

public T Value {
    get {
        if (!hasValue) {
            ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_NoValue);
        }
        return value;
    }
}

In other words, the cast calls the property and the exception is thrown by the property. So, no, there is no difference between the two options.

Style-wise, we are then into subjectivity. Both are valid and both have been explicitly allowed for by the designers of the type. I'd opt for using the property option, but that's purely personal choice.

Related Topic