Possible Duplicate:
Which is preferred: Nullable<>.HasValue or Nullable<> == null?
I’m working in a codebase which uses both of the following forms for “safely” getting values out of Nullable types. For example, if foo is a Nullable (int?):
if (foo != null) {
value = (int)foo;
}
if (foo.HasValue) {
value = foo.Value;
}
I prefer the second form, but is there any particular context which might make the first (or the second, for that matter) certainly preferred over the other?
The first and second are exactly equivalent, and compile down to the same IL.
EDIT: They do indeed generate the same IL, like this:
This is guaranteed by section 7.10.9 of the C# 4 spec (or the equivalent in other versions).
Basically – use whichever form you and your team find more readable.
Anton highlighted the null-coalescing operator – while Anton’s code isn’t equivalent to yours, it’s an operator that you definitely should be familiar with, as it can really make for nice code.