-1

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?

Community
  • 1
  • 1
lance
  • 16,092
  • 19
  • 77
  • 136

3 Answers3

3

The first and second are exactly equivalent, and compile down to the same IL.

EDIT: They do indeed generate the same IL, like this:

  IL_000b:  ldloca.s   V_1
  IL_000d:  call       instance bool valuetype 
                           [mscorlib]System.Nullable`1<int32>::get_HasValue()
  IL_0012:  ldc.i4.0
  IL_0013:  ceq
  IL_0015:  stloc.2
  IL_0016:  ldloc.2
  IL_0017:  brtrue.s   IL_0023
  IL_0019:  nop
  IL_001a:  ldloca.s   V_1
  IL_001c:  call       instance !0 valuetype
                           [mscorlib]System.Nullable`1<int32>::get_Value()
  IL_0021:  stloc.0

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Yes, it *is* guaranteed that the compiler will use the Value property, if the compiler conforms with the spec (version 3.0 section 7.9.9, "Equality operators and null"). – phoog Nov 30 '11 at 22:30
  • @phoog: Good catch. It's section 7.10.9 in the C# 4 spec. Will edit. – Jon Skeet Nov 30 '11 at 22:44
2

I tend to use the second form because it represents what a Nullable actually is -- a struct with two members.

Joshua
  • 40,822
  • 8
  • 72
  • 132
1

I personally prefer

var value = foo ?? 0;
Anton Gogolev
  • 113,561
  • 39
  • 200
  • 288
  • That's not the same though - that will change the value of `value` *even if `foo` is null`, which isn't the case with the code in the question. – Jon Skeet Sep 22 '11 at 18:23
  • Maybe so, Jon, but you'll get a compile error if `value` is uninitialized before you use it, so might as well make the code more readable by initializing it to the default value like Anton has suggested using the null coalescing operator `??`. – FMM Sep 22 '11 at 20:23