Search code examples
c#.netoperatorsnull-coalescing

?? or .GetValueOrDefault()


I have properties type int? and decimal? that are being used in a calculation. If the value of any of them is null it has to default to 0. I'm trying to decide between using null-coalescing or GetValueOrDefault() which will also default to 0 if a value is null. Which approach would be better in terms of readability and performance (if there is any noticeable difference)?

First:

public decimal MyMethod(int memberId)
{ 
    var dto = GetDtoValue(memberId);
 return (dto.PropertyOne ?? 0)
      + (dto.PropertyTwo ?? 0)
      + (dto.PropertyThree ?? 0)
      - (dto.PropertyFour ?? 0)
      + ...
}

Second:

public decimal MyMethod(int memberId)
    { 
        var dto = GetDtoValue(memberId);
     return dto.PropertyOne.GetValueOrDefault())
          + dto.PropertyTwo.GetValueOrDefault())
          + dto.PropertyThree.GetValueOrDefault())
          - dto.PropertyFour.GetValueOrDefault())
          + ...
    }

Solution

  • Readability

    This is opinion of course, but

    • I read ?? 0 and feel like it's clear immediately
    • I read GetValueOrDefault and have to take a second to think about the type and then that type's default value (and I don't see this as a problem, just pointing out the "mental mapping")

    Performance

    This article holds that GetValueOrDefault compiles to CIL that's technically faster, but the improvement is a micro-optimization at best.

    SharpLab, however, has both versions compiling to the exact same CIL (via Marc's comment below), which would make their performance identical.

    Either way, the performance difference is insignificant at best, and nonexistent at worst, which means that readability should be prioritized.