Null-conditional operator - CSharp Language Basics

CSharp examples for Language Basics:Null Operator

Introduction

The ?. operator is the null-conditional.

It can call methods and access members like the standard dot operator, except that if the operand on the left is null, the expression evaluates to null instead of throwing a NullReferenceException:

Demo Code

using System;//from ww  w.  j a  v a 2 s  .c  om
class Test
{
   static void Main(){
      System.Text.StringBuilder sb = null;
      string s = sb?.ToString();  // No error; s instead evaluates to null
      Console.WriteLine (s);
   }
}

The following two lines are equivalent:

string s = sb?.ToString();  // No error; s instead evaluates to null
     
string s = (sb == null ? null : sb.ToString());

Related Tutorials