In our C# code, we already test if a variable is null before attempting to access it.
if (myInt.HasValue) {
var yourInt = myInt;
// do something with yourInt
}
My question: is there a difference in using the nullable property as if it wasn't after it has been tested versus the following?
if (myInt.HasValue) {
var yourInt = myInt.Value; // see the difference?
// do something with yourInt
}
Is this just a matter of preference or is there a distinct reason or performance impact for using .Value
even after the nullable object has passed that test?
UPDATE
I expanded on my second example, we already test with HasValue
, but there we use .Value
to access the value.
UPDATE 2
I updated the examples to use var
s because in our code we don't actually use int
types, sorry about the poor example. In our code, we actually just use the object inside an NHibernate Criteria query - Expression.Eq("thing", myInt)
query.
This doesn't throw a compilation error. I was trying to simplify the example to get to the root of my question without getting NHibernate involved. Sorry if this invalidates some of the answers. I was just trying to see if there is a hit on performance if we force another method to find the value versus explicitly calling .Value
.