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;
T?
toT
, 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.