The null-conditional operator helps you safely access members or elements of an object that might be null, avoiding errors.
Null-conditional operator in C Sharp (C#)
object?.Member object?[index] object?.Method()
The ?. operator returns null if the object is null instead of throwing an error.
You can use it with properties, methods, and indexers.
Name from person. If person is null, name becomes null instead of crashing.Person person = null;
string name = person?.Name;person and Name are not null.int? length = person?.Name?.Length;FirstOrDefault() on list only if list is not null.var firstItem = list?.FirstOrDefault();
int? value = dictionary?["key"];
This program shows how the null-conditional operator ?. safely accesses the Name property. When person is null, it returns null instead of crashing. When person has a value, it prints the name.
using System; class Person { public string Name { get; set; } } class Program { static void Main() { Person person = null; // Using null-conditional operator to safely get Name string name = person?.Name; if (name == null) Console.WriteLine("Name is null because person is null."); else Console.WriteLine(name); person = new Person { Name = "Alice" }; // Now person is not null Console.WriteLine(person?.Name); } }
The null-conditional operator helps avoid many if (obj != null) checks.
If the left side is null, the whole expression returns null immediately.
You can combine it with the null-coalescing operator ?? to provide default values.
The null-conditional operator ?. safely accesses members of objects that might be null.
It helps prevent errors by returning null instead of throwing exceptions.
Use it to write cleaner and safer code when dealing with nullable objects.
Practice
?. do in C#?Solution
Step 1: Understand the purpose of the null-conditional operator
The operator?.is used to access members of an object only if the object is not null.Step 2: Behavior when object is null
If the object is null, instead of throwing an exception, it returns null safely.Final Answer:
It safely accesses a member only if the object is not null, otherwise returns null. -> Option AQuick Check:
Null-conditional operator = safe member access [OK]
- Thinking it throws an exception on null
- Confusing it with null-coalescing operator
- Assuming it converts null to empty string
Length property of a string variable text that might be null?Solution
Step 1: Identify correct null-conditional syntax
The null-conditional operator is?.placed before the member name, liketext?.Length.Step 2: Match variable type with possible null
Sincetextmight be null, the resulttext?.Lengthis nullable, so useint?to hold it.Final Answer:
int? length = text?.Length; -> Option BQuick Check:
Correct syntax = int? length = text?.Length; [OK]
- Placing ? after Length instead of before
- Using non-nullable int for nullable result
- Adding extra dots or question marks
string? name = null; int? length = name?.Length; Console.WriteLine(length == null ? "Null" : length.ToString());
Solution
Step 1: Evaluate null-conditional operator on null string
The variablenameis null, soname?.Lengthreturns null safely.Step 2: Check output logic
The code prints "Null" iflengthis null, otherwise prints the length. Sincelengthis null, it prints "Null".Final Answer:
Null -> Option AQuick Check:
Null string length = null, prints "Null" [OK]
- Expecting 0 instead of null
- Thinking it throws exception
- Confusing null with empty string
Person? person = null; int age = person?.Age; Console.WriteLine(age);
Solution
Step 1: Analyze the type of person?.Age
The expressionperson?.Agereturnsint?(nullable int) because person might be null.Step 2: Check assignment compatibility
Variableageis declared asint(non-nullable), so assigningint?tointwithout conversion causes a compile error.Final Answer:
Cannot assign nullable int to non-nullable int without cast. -> Option CQuick Check:
Nullable to non-nullable assignment needs cast [OK]
- Ignoring nullable type returned by ?. operator
- Assuming no error on assignment
- Thinking null-conditional operator is invalid here
Person objects where some may be null, how can you safely get a List<int> of their ages (with 0 for null persons) using the null-conditional operator?List<Person?> people = new() { new Person(30), null, new Person(25) };
var ages = ???;Choose the correct code to replace
???.Solution
Step 1: Understand the list and nulls
The list containsPerson?objects, some are null, so accessingAgeneeds safe access.Step 2: Use null-conditional with fallback
p?.Agesafely accesses Age or returns null; using?? 0replaces null ages with 0 to avoid nullable list.Step 3: Check other options
people.Select(p => p?.Age).ToList(); returns nullable ints, people.Select(p => p.Age).ToList(); throws exception on null, people.Select(p => p.Age ?? 0).ToList(); is invalid becausepcan be null.Final Answer:
people.Select(p => p?.Age ?? 0).ToList(); -> Option DQuick Check:
Safe access with fallback = people.Select(p => p?.Age ?? 0).ToList(); [OK]
- Not handling null Person objects
- Forgetting to provide fallback value
- Assuming Select handles nulls automatically
Ready to prove it?
Pass the test and this pattern moves unknown
