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 vars 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.
will throw if
HasValueisfalse.Thus, if you don’t want to experience
InvalidOperationExceptions, checkHasValuefirst.Note that
is not legal (compile-time failure) because there is no implicit conversion from
int?toint(what if the value isnull; there’s no reasonable value to cast theint?to). You can say:Note that this will throw if
myIntisnullthough, just like accessingValue.One last note, if you’re okay with accepting a default value, you can use the null coalescing operator and say:
This is equivalent to:
No. Performance is totally irrelevant here, especially if there is a database involved. This is absolutely not going have any meaningful performance difference, and will certainly not be a bottleneck. Just write the clearest code. Frankly, I find
.Valueto be the clearest.