Skip to content

Null-conditional operators C# 6.0code reduction

Safely access members on potentially null objects.

Checking if variables are null before they are used is a very common requirement.

The ?. and ?[] operators allow you to access methods, properties or indexers without having to worry if the variable you are using is null. If it is then the result will just be null as well.

Code ​

csharp
string b = a?.ToString();
int? length = customer?.Name?.Length;
PropertyChanged?.Invoke(this, args);
csharp
string b = null;
if (a != null)
    b = a.ToString();

int? length = null;
if (customer != null && customer.Name != null)
    length = customer.Name.Length;

var handler = PropertyChanged;
if (handler != null)
    handler(this, args);

Notes ​

  • Evaluation short-circuits, so if customer is null nothing to the right of ?. in the chain is evaluated
  • Accessing a value-type member such as Length produces a nullable result (int?)
  • The expression on the left is evaluated only once, making ?.Invoke a thread-safe way to raise events without copying the delegate to a local first
  • Use in conjunction with the ?? Null-coalescing operator C# 2.0 to provide a final default value
  • The ??= null-coalescing assignment operator C# 8.0 is also useful in similar scenarios
  • Null-conditional assignment C# 14.0 allows ?. on the left of an assignment

More information ​

Powered by Intracia