AdvancedLesson 17 of 205 min read

Nullable Types, Generics and Delegates

Learn how nullable reference types let the compiler catch null mistakes, how generic methods with constraints work, and how delegates, lambdas and events connect code, with the compiler's real warnings.

In this lesson you will

  • Read nullable reference warnings
  • Write a generic method with a constraint
  • Use Func, Action and lambdas
  • Raise and handle an event

About 28 minutes

The null that crashed the till

Omar’s till program looks up a customer by name, and for a customer that does not exist the lookup returns null. The next line calls a method on it, and the till crashes with a NullReferenceException. Tony Hoare, who introduced null references into a language in 1965, later called it his billion-dollar mistake. C# 8 added nullable reference types to help: when the feature is on, which is the default in new projects, a reference type such as string means “never null”, and string? means “may be null”, and the compiler warns whenever you use a maybe-null value without checking it.

Generics let you write one method or class for many types. A constraint, written with where, says what the type must be able to do, so that the body can rely on it: where T : IComparable promises that two values can be compared. Delegates are types for methods: Func is any method that takes an int and returns an int, and Action is a method that returns nothing. Lambdas are short ways to write such methods. An event is a delegate with rules: other code can subscribe and unsubscribe, but only the owner can raise it, which makes events the standard way for one object to tell others that something happened without knowing who listens.

Idea Syntax Purpose
Maybe-null string? name Compiler tracks null
Null check if (name is not null) Narrows to non-null
Null-conditional name?.Length Stops at null
Generic constraint where T : IComparable Allows comparing
Delegate Func A method as a value
Event event Action? Notify subscribers
var customers = new Dictionary<string, string> { ["Ana"] = "ana@example.test", ["Ben"] = "ben@example.test" };
string? Find(string name) => customers.TryGetValue(name, out var mail) ? mail : null;

string? found = Find("Cy");
Console.WriteLine($"lookup for Cy: {found ?? "not found"}");
Console.WriteLine($"safe length: {found?.Length ?? -1}");
if (found is not null) Console.WriteLine(found.Length);
try { Console.WriteLine(Find("Cy").Length); }
catch (NullReferenceException) { Console.WriteLine("the unchecked call crashed: NullReferenceException"); }

static T Biggest<T>(IEnumerable<T> items) where T : IComparable<T>
{
    T best = items.First();
    foreach (var x in items) if (x.CompareTo(best) > 0) best = x;
    return best;
}
Console.WriteLine($"biggest int: {Biggest(new[] { 4, 9, 2 })}, biggest string: {Biggest(new[] { "tea", "latte", "mocha" })}, biggest decimal: {Biggest(new[] { 3.2m, 2.1m })}");

Func<decimal, decimal> addTax = p => Math.Round(p * 1.19m, 2);
Action<string> shout = s => Console.WriteLine(s.ToUpper());
Console.WriteLine($"Func: 10.00 with tax = {addTax(10m)}");
shout("delegates are values");

var till = new Till();
var log = new List<string>();
till.Sold += item => log.Add("listener 1 saw " + item);
till.Sold += item => log.Add("listener 2 saw " + item);
till.Sell("latte"); till.Sell("tea");
Console.WriteLine(string.Join(" | ", log));

class Till
{
    public event Action<string>? Sold;
    public void Sell(string item) => Sold?.Invoke(item);
}
Program.cs(8,25): warning CS8602: Dereference of a possibly null reference. [app.csproj]
lookup for Cy: not found
safe length: -1
the unchecked call crashed: NullReferenceException
biggest int: 9, biggest string: tea, biggest decimal: 3.2
Func: 10.00 with tax = 11.90
DELEGATES ARE VALUES
listener 1 saw latte | listener 2 saw latte | listener 1 saw tea | listener 2 saw tea

The compiler saw the mistake before the program ran: the first lines of the output are warnings, CS8602, and CS8602 means that something that may be null is dereferenced. In the program, the safe versions behave: the lookup for Cy printed “not found” with the ?? operator, the null-conditional gave a length of -1 through ?. and ??, and the null check with is not null guarded the direct use. The unchecked call, which the warning pointed at, did crash with a NullReferenceException, exactly as predicted.

The generic method Biggest worked for ints, strings and decimals, giving 9, “tea” and 3.2, because all of them implement IComparable, which is what the constraint demands. The Func calculated 10.00 plus 19 percent as 11.90, and the Action printed its argument in capitals. The event had two subscribers, and each sale reached both in the order they subscribed: listener 1 saw latte | listener 2 saw latte | listener 1 saw tea | listener 2 saw tea. The ?.Invoke call is the safe way to raise an event, because an event with no subscribers is null.

Check by hand: 10.00 x 1.19 = 11.90. “tea” is the biggest of “tea”, “latte” and “mocha” in dictionary order because t comes after m and l. With two subscribers and two sales, the log has four entries.

Do not silence warnings with the bang operator lightly

Writing x! tells the compiler to trust you. If you are wrong, the program crashes at run time. Prefer checks, and use ! only when you can prove a value is not null.

Turn on nullable reference types in every project

New projects have it on by default. It converts a whole class of run-time crashes into compile-time warnings, and you can treat warnings as errors in your build.

About this course

Every program in this lesson was built and run with the .NET 8 SDK and C# 12 while the course was written. .NET and C# release every year, so check the official Microsoft documentation for the current version and for features added after .NET 8. The first lines of the output are real compiler warnings.

Practice

Make a method that finds a menu item by name and returns MenuItem?. Call it with a missing name and fix every warning that the compiler gives. Write a generic method Smallest and a delegate that filters a list, and add an event that fires when a stock level drops below a limit.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What does string? mean with nullable reference types on?

  1. The value is a number
  2. The value may be null
  3. The string is empty
  4. The string is long

string alone means never null.

What does CS8602 warn about?

  1. Dereferencing something that may be null
  2. A missing semicolon
  3. A wrong type
  4. A slow loop

It is a compile-time warning.

What does where T : IComparable do?

  1. Requires that values of T can be compared
  2. Makes T an int
  3. Hides T
  4. Creates a class

The body may call CompareTo.

What is Func?

  1. A class
  2. A loop
  3. A file
  4. A delegate for a method that takes an int and returns an int

Lambdas fit it.

Who can raise an event?

  1. Any code
  2. Only subscribers
  3. Only the compiler
  4. Only the class that declares it

Others can subscribe and unsubscribe.

Summary

  • Nullable reference types make the compiler track null.
  • Generic constraints state what a type must be able to do.
  • Delegates and lambdas treat methods as values.
  • Events notify subscribers; only the owner raises them.

Next lesson

Lesson 18 covers professional practice: design, disposal, configuration and project structure.

Questions

What is the bang operator?

The ! after an expression, which tells the compiler to treat a maybe-null value as not null. It does not check anything at run time.

Is a delegate the same as an interface?

They both describe what can be called. A delegate describes a single method signature, and an interface can describe many members.

What about multicast delegates?

A delegate can hold several methods, and invoking it calls all of them in order. Events are built on this.

Progress is saved in this browser.