Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

?? or .GetValueOrDefault() [closed]

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())
          + ...
    }
like image 656
Roman Svitukha Avatar asked Jul 19 '26 23:07

Roman Svitukha


1 Answers

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.

like image 50
egnomerator Avatar answered Jul 21 '26 11:07

egnomerator



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!