The Null Coalescing Operator (??) - CSharp Language Basics

CSharp examples for Language Basics:Null Operator

Introduction

The null coalescing operator is used with the nullable value types and reference types.

It converts a value to another nullable or normal value, where an implicit conversion is possible.

If the value is null, then the operator returns the value of the second operand, otherwise it returns the value of the first operand.

Demo Code

using System;//w  w  w  . ja va  2 s .c o m
class MainClass{
   static void Main(string[] args) {
      double? num1 = null;
      double? num2 = 3.14157;
      double num3;
      num3 = num1 ?? 5.34;
      Console.WriteLine(" Value of num3: {0}", num3);
      num3 = num2 ?? 5.34;
      Console.WriteLine(" Value of num3: {0}", num3);
   }
}

Result


Related Tutorials