Null-Conditional Operator

suggest change

The ?. operator is syntactic sugar to avoid verbose null checks. It’s also known as the Safe navigation operator.

Class used in the following example:

public class Person
{
    public int Age { get; set; }
    public string Name { get; set; }
    public Person Spouse { get; set; }
}

If an object is potentially null (such as a function that returns a reference type) the object must first be checked for null to prevent a possible NullReferenceException. Without the null-conditional operator, this would look like:

Person person = GetPerson();

int? age = null;
if (person != null)
    age = person.Age;

The same example using the null-conditional operator:

Person person = GetPerson();

var age = person?.Age;    // 'age' will be of type 'int?', even if 'person' is not null

Chaining the Operator

The null-conditional operator can be combined on the members and sub-members of an object.

// Will be null if either `person` or `person.Spouse` are null
int? spouseAge = person?.Spouse?.Age;

Combining with the Null-Coalescing Operator

The null-conditional operator can be combined with the null-coalescing operator to provide a default value:

// spouseDisplayName will be "N/A" if person, Spouse, or Name is null
var spouseDisplayName = person?.Spouse?.Name ?? "N/A";

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Null-Conditional Operators:
* Null-Conditional Operator

Table Of Contents
7 Null-Conditional Operators
17 Regex
19 Arrays
21 Enum
22 Tuples
24 GUID
27 Looping
36 Casting
46 Methods
88 Events
92 Structs
104 Indexer
106 Stream
107 Timers
109 Threading
127 Caching
135 Pointers
147 C# Script