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
C#
string b = a?.ToString();
C#
string b = null;
if (a != null)
b = a.ToString();
Notes
- 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