🏠 VisualStudioTutor.com  ·  C# Tutorial Home  ·  C# Lesson 17 of 40
Lesson 17 of 40 Core C# Intermediate ⏱ 35 min

Nullable Reference Types & Null Safety

Use nullable annotations and null-safe operators to prevent common NullReferenceException bugs before they reach production.

Part 1: What You Will Learn

Use nullable annotations and null-safe operators to prevent common NullReferenceException bugs before they reach production.

  • Understand the difference between string and string? when nullable reference types are enabled.
  • Use ?. and ?? to read values safely without long chains of null checks.
  • Use required members when an object must be initialized with important data.
  • Respond to compiler nullable warnings instead of hiding them with the null-forgiving operator (!).

Project setup: Create a .NET 10 Console App in Visual Studio 2026. Nullable reference types are enabled by default in modern .NET projects.

Part 2: Topic-Specific Working Example

The following example is written specifically for this lesson. Create the project described above, enter the code, run it, and then change some values to observe how the feature behaves.

#nullable enable

public sealed class Customer
{
    public required string Name { get; init; }
    public string? Email { get; set; }
}

static Customer? FindCustomer(int id)
{
    return id == 1
        ? new Customer { Name = "Aisha", Email = " AISHA@example.com " }
        : null;
}

Customer? customer = FindCustomer(1);

// ?. stops the member-access chain when a value is null.
// ?? supplies a fallback value.
string name = customer?.Name ?? "Guest";
string email = customer?.Email?.Trim().ToLowerInvariant()
               ?? "No email supplied";

Console.WriteLine($"Customer: {name}");
Console.WriteLine($"Email: {email}");

Customer? missingCustomer = FindCustomer(99);
Console.WriteLine(missingCustomer?.Name ?? "Customer not found");

Part 3: How the Code Works

  • `Customer?` explicitly says that the variable may contain null; `Customer` says callers should expect a real object.
  • `customer?.Email?.Trim()` safely stops if either customer or Email is null.
  • `??` provides a value when the expression on its left evaluates to null.
  • `required Name` tells the compiler that callers must initialize Name when constructing a Customer.

Part 4: Mini Project & Practice

Mini project: build a Customer Lookup console app. Add PhoneNumber? and Address? properties, then print a complete customer summary without producing nullable warnings or throwing NullReferenceException.

Tip: Type the code yourself in Visual Studio 2026, run it, then deliberately change one part at a time. The goal is to understand the feature rather than simply copy the finished example.

When you are comfortable with this lesson, continue to Lesson 18.

C# in Visual Studio 2026

📘 This lesson is part of the book C# in Visual Studio 2026 by Dr. Liew Voon Kiong.

View on Amazon Kindle Edition