Essential C# Null-Conditional Operators  Suggest an edit

Avoiding NullReferenceExceptions

var person = new Person
{
    Address = null;
};

var city = person.Address.City; //throws a NullReferenceException
var nullableCity = person.Address?.City; //returns the value of null

This effect can be chained together:

var person = new Person
{
    Address = new Address
    {
        State = new State
        {
            Country = null
        }
    }
};

// this will always return a value of at least "null" to be stored instead
// of throwing a NullReferenceException
var countryName = person?.Address?.State?.Country?.Name;

Table Of Contents
8 Null-Conditional Operators
22 Enum
25 GUID
107 Stream
108 Timers
  ↑ ↓ to navigate     ↵ to select     Esc to close