Handling null safely
Course contents (16 lessons)
- Getting started
- Installing the .NET 10 SDK and checking it works
- Your first console app and top-level statements
- The building blocks
- Variables and basic types
- Working with strings and interpolation
- Reading input and writing output
- Making decisions and repeating work
- Conditionals and switch expressions
- Loops: for, while, do and foreach
- Collections and methods
- Arrays and List of T
- Writing your own methods
- Objects and classes
- Classes and objects
- Properties, encapsulation and object initialisers
- Handling null safely
- Errors and files
- Exceptions: try, catch, finally and throw
- Reading and writing files
- Final project: expense tracker
- Expense tracker, part 1: planning, model and storage
- Expense tracker, part 2: the menu and summaries
The most common crash in C#
Null means "no object here". A variable of a reference type, such as string or any class you write, can hold null. If you try to use a member of a null reference, the program throws a NullReferenceException. Everyone who writes C# meets this error often. The tools in this lesson reduce how often.
Nullable reference types
New projects enable nullable reference types, which you saw as <Nullable>enable</Nullable> in the project file. With this feature on, the compiler treats string as "never null" and string? as "may be null". It then warns you when you might use a possibly-null value without checking it. The warnings do not change how the program runs. They help you find the bug before the user does.
string? input = null;
// Check before use
if (input != null)
{
Console.WriteLine(input.Length);
}
// Null-conditional operator: stops and gives null
int? length = input?.Length;
Console.WriteLine(length is null ? "no text" : length.ToString());
// Null-coalescing operator: provide a fallback
string display = input ?? "(empty)";
Console.WriteLine(display);
// Null-coalescing assignment: set only if null
input ??= "default value";
Console.WriteLine(input);
// A realistic case
var customers = new List<Customer>
{
new Customer { Name = "Ayesha", Email = "ayesha@example.com" },
new Customer { Name = "Bilal" }
};
foreach (Customer c in customers)
{
string email = c.Email?.ToLowerInvariant() ?? "no email on file";
Console.WriteLine($"{c.Name}: {email}");
}
// Pattern matching with is
object value = "hello";
if (value is string text && text.Length > 3)
{
Console.WriteLine($"Long text: {text}");
}
Customer? found = customers.FirstOrDefault(c => c.Name == "Zainab");
if (found is null)
{
Console.WriteLine("Customer not found.");
}
class Customer
{
public required string Name { get; init; }
public string? Email { get; init; }
}
Walking through it
We declare input as string? and set it to null. The plain if (input != null) check is the oldest tool, and still a good one. After the check, the compiler knows the value is not null inside the braces and stops warning.
The operator ?. is null-conditional. input?.Length means "if input is null, the whole expression is null, otherwise take its length". Because the result might be null, its type is int?, a nullable int. A nullable value type can hold a number or null.
The operator ?? gives a fallback. The line input ?? "(empty)" reads "use input, or this text if it is null". The ??= operator assigns only when the variable is null.
In the customer loop, I chain two operators: c.Email?.ToLowerInvariant() ?? "no email on file". The first half is safe against a null email. The second half converts the null result into readable text. This pair appears constantly in real code.
The is keyword checks a type and creates a variable in one step. value is string text is true only if value really is a string, and then text is ready to use. found is null is the modern way to check for null. It cannot be fooled by a class that overloads ==.
FirstOrDefault returns null (for classes) when nothing matches. That is a place where null enters your program legitimately. Handle it.
The dangerous operator
You may see value! with an exclamation mark. It tells the compiler "I know this is not null, stop warning". If you are wrong, you get the crash anyway. Use it rarely, and only when you can explain why it is safe.
Common mistakes
- Turning off the warnings. They are the point of the feature.
- Using
!to silence the compiler instead of handling the case. - Returning null for a list. Return an empty list. Callers then never need a check.
- Assuming input is not null.
Console.ReadLine(), dictionary lookups withTryGetValue, and search methods can all hand you null.
Try it yourself
- Write a method
GetInitial(string? name)that returns the first letter in uppercase, or "?" if the name is null or empty. - Create a
Customerwith an optional phone number and print "n/a" when it is missing. - Remove one null check from the example and read the compiler warning that appears.
string? input = null;
// Check before use
if (input != null)
{
Console.WriteLine(input.Length);
}
// Null-conditional operator: stops and gives null
int? length = input?.Length;
Console.WriteLine(length is null ? "no text" : length.ToString());
// Null-coalescing operator: provide a fallback
string display = input ?? "(empty)";
Console.WriteLine(display);
// Null-coalescing assignment: set only if null
input ??= "default value";
Console.WriteLine(input);
// A realistic case
var customers = new List<Customer>
{
new Customer { Name = "Ayesha", Email = "ayesha@example.com" },
new Customer { Name = "Bilal" }
};
foreach (Customer c in customers)
{
string email = c.Email?.ToLowerInvariant() ?? "no email on file";
Console.WriteLine($"{c.Name}: {email}");
}
// Pattern matching with is
object value = "hello";
if (value is string text && text.Length > 3)
{
Console.WriteLine($"Long text: {text}");
}
Customer? found = customers.FirstOrDefault(c => c.Name == "Zainab");
if (found is null)
{
Console.WriteLine("Customer not found.");
}
class Customer
{
public required string Name { get; init; }
public string? Email { get; init; }
}
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account