C# Interview Question #85

What are the null-conditional operators ?. and ?[] in C#?

Advanced C# Language Features Mid-Level Intermediate

Quick Interview Answer

Null-conditional operators safely access a member or index only when the target object is not null.

Detailed Explanation

Null-conditional operators safely access a member or index only when the target object is not null.

If the target is null, the expression returns null instead of throwing NullReferenceException. They are commonly combined with the null-coalescing operator.

They make optional navigation concise, but developers should still understand whether null is valid in the domain instead of using null-conditional access to hide unexpected null values.

Code Example

Customer? customer = GetCustomer();

string city = customer?.Address?.City ?? "Unknown";

int? firstLength = names?[0]?.Length;