Tutorials / C# for Beginners / Handling null safely

Handling null safely

12 min read csharp
Course contents (16 lessons)
  1. Getting started
  2. Installing the .NET 10 SDK and checking it works
  3. Your first console app and top-level statements
  4. The building blocks
  5. Variables and basic types
  6. Working with strings and interpolation
  7. Reading input and writing output
  8. Making decisions and repeating work
  9. Conditionals and switch expressions
  10. Loops: for, while, do and foreach
  11. Collections and methods
  12. Arrays and List of T
  13. Writing your own methods
  14. Objects and classes
  15. Classes and objects
  16. Properties, encapsulation and object initialisers
  17. Handling null safely
  18. Errors and files
  19. Exceptions: try, catch, finally and throw
  20. Reading and writing files
  21. Final project: expense tracker
  22. Expense tracker, part 1: planning, model and storage
  23. 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 with TryGetValue, and search methods can all hand you null.

Try it yourself

  1. Write a method GetInitial(string? name) that returns the first letter in uppercase, or "?" if the name is null or empty.
  2. Create a Customer with an optional phone number and print "n/a" when it is missing.
  3. Remove one null check from the example and read the compiler warning that appears.
csharp
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