Skip to main content

How to Use the Null-Conditional Operator ?. in C#

· 4 min read
Jagdish Kumawat
Founder @ Dewiride

name.Length throws a NullReferenceException when name is null. Write name?.Length instead and C# checks first: it reads Length when there's a name, and gives back null when there isn't.

Syntax​

Syntax
<result> = <value>?.<Member>;
<result> = <collection>?[<index>];
PartWhat it does
<value>?.<Member>Reads <Member> when <value> isn't null; otherwise the whole expression is null.
<collection>?[<index>]The same check for an element: reads <collection>[<index>] only when <collection> isn't null.
<result>Receives the member's value or null. For a member of a value type, such as int, the result is the nullable int?.

Microsoft's member access operators reference: "A null-conditional operator applies a member access (?.) or element access (?[]) operation to its operand only if that operand evaluates to non-null. Otherwise, it returns null."

The Example​

The example reads the Length of a name twice: once while the name is null and once after it's set to Leo. It then stores the result in a variable and checks whether it holds a value.

Prerequisites​

  • The .NET 10 SDK or newer, which runs a single .cs file with dotnet run. This guide uses .NET SDK 10.0.404.

Step 1: Write the Code​

Create a file named main.cs in an empty folder:

main.cs, which prints name?.Length while name is null and again after name is set to Leo, then stores name?.Length in an int? called length and prints length.HasValue.

main.cs
string? name = null;
Console.WriteLine(name?.Length);

name = "Leo";
Console.WriteLine(name?.Length);

int? length = name?.Length;
Console.WriteLine(length.HasValue);

int? is an int that may also be null. HasValue tells you which one it holds.

Step 2: Run It​

Terminal
dotnet run main.cs
Output

3
True

A zsh terminal where dotnet run main.cs prints an empty line, then 3 and True.

The first line is empty: name was null, so name?.Length was null too, and Console.WriteLine printed nothing, without an exception. After name = "Leo", the same expression returned 3, and length held a value. The command is the same in zsh, bash and PowerShell.

Why the Result Is an int?​

Length is an int, but name?.Length can also be null, so its type is int?. The reference: "If a.x or a[x] is of a non-nullable value type T, a?.x or a?[x] is of the corresponding nullable value type T?." Storing it in a plain int doesn't compile:

main.cs
string? name = "Leo";
int length = name?.Length;
Console.WriteLine(length);
Output
/Users/you/demo/main.cs(2,14): error CS0266: Cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast?)
/Users/you/demo/main.cs(2,14): warning CS8629: Nullable value type may be null.

The build failed. Fix the build errors and run again.

Use int?, as the example does, or give a fallback for null with ??, as in int length = name?.Length ?? 0;.

Common Mistakes​

MistakeWhat happensDo this instead
Storing name?.Length in an interror CS0266: Cannot implicitly convert type 'int?' to 'int'Store it in an int?, or add ?? 0
Writing name.Length for a value that may be nullNullReferenceException when it's nullWrite name?.Length
Printing the result without handling nullAn empty line, which is easy to missCheck HasValue, or give a fallback with ??

Troubleshooting​

SymptomLikely causeFix
CS0266 with int? and intA null-conditional result stored in a non-nullable typeUse int? or ?? <fallback>
An empty line where you expected a numberThe value before ?. was nullCheck where the value should have been set

FAQ​

What happens in a longer chain like a?.B.C?​

The check stops the whole chain. The reference: "The null-conditional operators are short-circuiting. That is, if one operation in a chain of conditional member or element access operations returns null, the rest of the chain doesn't execute."

Does ?. work on method calls?​

Yes. name?.ToUpper() calls ToUpper only when name isn't null, and is null otherwise.

Conclusion​

value?.Member reads the member only when the value isn't null, and returns null instead of throwing. For a value-type member such as Length, the result is an int?: keep it in an int?, or turn null into a default with ??.

Additional Resources​