Gracefully handle null numerals with GetValueOrDefault()

11/22/2021

I've often written code like:

short? value = 2;
short doubleIt = (value ?? 0) * 2;

Notice on the second line that the null coalescing (??) operator requires parenthesis around it before multiplying it by 2. Another options is to use GetValueOrDefault(), as such:

short? value = 2;
short doubleIt = value.GetValueOrDefault() * 2;

It's a subtle difference, but helpful at times. My primary reason for writing this short article is to get me to remember to start using it.


Please register or login to add a comment.

Comments (displaying 1 - 1):
No comments yet! Be the first...


  • C#/.NET
  • T-SQL
  • HTML/CSS
  • JavaScript/jQuery
  • .NET 8
  • ASP.NET/MVC
  • Xamarin/MAUI
  • WPF
  • Windows 11
  • SQL Server 20xx
  • Android
  • XBox
  • Arduino
  • Skiing
  • Rock Climbing
  • White water kayaking
  • Road Biking