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:
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?
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;