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/Core
  • T-SQL
  • HTML/Javascript/jQuery
  • ASP.NET/MVC
  • .NET Core
  • ADO.NET/EF
  • WPF
  • Xamarin/MAUI
  • Windows 10
  • SQL Server 20xx
  • Android
  • XBox One
  • Skiing
  • Rock Climbing
  • White water kayaking
  • Road Biking