Null-Conditional Operator C# with Example



Null-Conditional Operator C# with Example

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"; 

0 Comment's

Comment Form

Submit Comment