A NullReferenceException happens when code uses a reference that points at nothing. It's among the most common crashes in C# programs. Nullable reference types turn that runtime crash into a compile-time warning, by making "this might be null" part of a variable's type.
Turning it on
Downloadable projects enable this for all files in their project file. In the browser, a file starts it with #nullable enable. Now string promises a value, and string? admits there might not be one. This program compiles, with a warning, and then crashes as predicted.
#nullable enable
string? name = FindName(2);
Console.WriteLine(name.Length);
static string? FindName(int id) => id == 1 ? "Ana" : null;Check your prediction
warning CS8602
NullReferenceExceptionThese are warnings and not errors, so nothing stops you from ignoring them, and many teams turn them into errors with a project setting. This course's stated outputs must always run without warnings.
Ways to handle null
After a check, the compiler knows that the value isn't null. It tracks this through the code, which is called flow analysis. ?. reads a member only if the value isn't null, giving null otherwise, and ?? supplies a fallback.
#nullable enable
string? missing = null;
string? present = "Ana";
Console.WriteLine(missing?.Length);
Console.WriteLine(present?.Length);
Console.WriteLine(missing ?? "unknown");
if (present is not null)
{
Console.WriteLine(present.ToUpper());
}
if (present is { Length: > 2 } text)
{
Console.WriteLine(text);
}
missing ??= "assigned";
Console.WriteLine(missing);Check your prediction
3
unknown
ANA
Ana
assignedThe first line is blank, because the value printed is null. ??= assigns only when the variable is currently null.
Fail early at a boundary
Nullable checks are only compile-time help. They aren't enforced when the program runs, so data from outside (or code that has ignored a warning) can still bring in a null. Guard public methods where it matters. !, the null-forgiving operator, tells the compiler "trust me". It adds no check, so use it rarely, and only when you can explain why it's safe.
#nullable enable
Console.WriteLine(new Greeter("Ana").Greet());
try
{
string? missing = null;
new Greeter(missing!);
}
catch (ArgumentNullException e)
{
Console.WriteLine(e.ParamName);
}
class Greeter
{
private readonly string name;
public Greeter(string name)
{
ArgumentNullException.ThrowIfNull(name);
this.name = name;
}
public string Greet() => $"Hello, {name}";
}Check your prediction
Hello, Ana
nameValue types too
int? is a nullable int, written Nullable<int> in full, and it has been in C# for much longer. It's a real wrapper with HasValue and Value. The ordering comparisons <, >, <= and >= are false whenever either side is null, which is worth remembering; == and != work as you'd expect, so null == null is true.
int? score = null;
Console.WriteLine(score.HasValue);
Console.WriteLine(score ?? 0);
Console.WriteLine(score > 10);
Console.WriteLine(score < 10);
score = 42;
Console.WriteLine(score.Value + 1);Check your prediction
False
0
False
False
43Fix it: The warning that came true
Find returns null when there's no match. The compiler warns about the last line. Run it anyway.
#nullable enable
string? name = Find(new[] { "Ana", "Ben" }, "Z");
Console.WriteLine(name.Length);
static string? Find(string[] names, string start)
{
foreach (string name in names)
{
if (name.StartsWith(start))
{
return name;
}
}
return null;
}Check your prediction
warning CS8602: Dereference of a possibly null reference.
NullReferenceExceptionWarning CS8602 predicted exactly this crash. The ? on string? says "may be null", and nothing between Find and .Length checked. Fix it to print 0 when there's no name.
Fix it
Use ?. so a null name gives a null length, and ?? to turn that into a default:
#nullable enable
string? name = Find(new[] { "Ana", "Ben" }, "Z");
Console.WriteLine(name?.Length ?? 0);
static string? Find(string[] names, string start)
{
foreach (string name in names)
{
if (name.StartsWith(start))
{
return name;
}
}
return null;
}0The ! operator (name!.Length) would silence the warning and keep the crash. Use it only when you know something the compiler can't, and treat every CS8602 as a crash report that hasn't happened yet.
Your turn
Find a manager's email
Records in the workspace link people to optional managers and optional emails. Write ManagerEmail(Person person), returning string?: the email of a person's manager, or null if either is missing. Write it as a single expression, then write Contact(Person person) which uses it and returns no contact when there's no result. Print the contact for Ana, Ben and Cy. A warning-free run is part of the goal.
When it works, it prints:
boss@example.com
no contact
no contact#nullable enable
var boss = new Person("Boss", null, "boss@example.com");
var quiet = new Person("Quiet", null, null);
var ana = new Person("Ana", boss, null);
var ben = new Person("Ben", quiet, null);
var cy = new Person("Cy", null, null);
Console.WriteLine(ana.Name);
record Person(string Name, Person? Manager, string? Email);Hint 1: the idea
?. can be chained, and the whole chain becomes null as soon as any step is null.
Hint 2: a first step
Begin with person.Manager?.Name and print it for each person, then swap in Email and add a fallback in the second method.
Show one solution
#nullable enable
var boss = new Person("Boss", null, "boss@example.com");
var quiet = new Person("Quiet", null, null);
var ana = new Person("Ana", boss, null);
var ben = new Person("Ben", quiet, null);
var cy = new Person("Cy", null, null);
Console.WriteLine(Contact(ana));
Console.WriteLine(Contact(ben));
Console.WriteLine(Contact(cy));
static string? ManagerEmail(Person person) => person.Manager?.Email;
static string Contact(Person person) => ManagerEmail(person) ?? "no contact";
record Person(string Name, Person? Manager, string? Email);boss@example.com
no contact
no contact?. handles both missing links in one expression: no manager, and a manager with no email, each give null. ManagerEmail is honest about that with its string? return type, and Contact is where the decision about what to show is made, once, with ??. Because Contact returns a plain string, nothing that calls it ever needs a null check.
Completion is saved in this browser only. It does not measure mastery.