C# 6.0 introduced new operator – null conditional operator ?.
The way it works is very simple. It checks if the left part of the expression is null and if it’s not it returns the right part. Otherwise, it returns null.
Simple example:
var thisWillBeNulll = someObject.NullProperty?.NestedProperty;
var thisWilllBeNestedProperty = someObject.NotNullProperty?.NestedProperty;
Executable example:
//Rextester.Program.Main is the entry point for your code. Don't change it.
//Compiler version 4.0.30319.17929 for Microsoft (R) .NET Framework 4.5
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Rextester
{
public class Person
{
public string Name { get; set; }
}
public class Dog
{
public Person Owner { get; set; }
}
public class Program
{
public static void Main(string[] args)
{
Dog dog = new Dog();
Console.WriteLine(dog.Owner?.Name == null);
// this will print True
dog.Owner = new Person() { Name = "Fred" };
Console.WriteLine(dog.Owner?.Name);
// this will print Fred
}
}
}
The above example can be executed here: https://rextester.com/TBC19437
Documentation: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/member-access-operators#null-conditional-operators–and-