6

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;

  • 1
    The scenario you have in mind is specifically casting a T? to T, and not to some other type, right? In that case I would always prefer using .Value; it is unambiguous that (1) we believe that the nullable has a value, and (2) that we intend to extract that value. – Eric Lippert Jan 5 '17 at 18:40
10

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.

  • Just for the record, do you know if there are specific guidelines (such as that of StyleCop) that recommend for or against using one of the two styles? – Sam Jan 4 '17 at 17:24
  • @Sam: sorry, I have no idea. I intensely dislike StyleCop, both because I disagree with many of its default behaviours and because it focuses on the minutiae and ignores the "bigger picture" of well written code. – David Arno Jan 5 '17 at 12:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.