Beginner · Arrays, strings and null · topic 13 of 43 · 30 min
null, nullable types and null-safe operators
Explanation
What is null?
A reference-type variable, such as a string or an array, holds an arrow to an object. null means the arrow points at nothing. It is useful to say "not known yet" or "not found". The danger is using it: asking for the length of nothing makes no sense, so the program crashes.
string? middleName = null;
Console.WriteLine(middleName.Length); // NullReferenceException at run timeValue types cannot be null... unless you add ?
Value types like int, double, decimal, bool and DateTime always have a value; an int is 0 by default, never null. Sometimes you need "no value", for example a student who has not taken the exam yet. Add ? to the type to make a nullable value type.
int? marks = null; // not taken yet
Console.WriteLine(marks.HasValue); // False
marks = 72;
Console.WriteLine(marks.Value); // 72
int sure = marks ?? 0; // 72, or 0 if marks were nullNullable reference types: help from the compiler
Since C# 8 you can switch on nullable reference types, and new projects have it on by default (<Nullable>enable</Nullable> in the .csproj). Then string means "should never be null" and string? means "may be null". The compiler tracks this and warns you when you might use a null. It does not change how the program runs; it is an early-warning system.
string name = null; // warning CS8600: converting null to non-nullable type
string? nick = GetNickname();
Console.WriteLine(nick.Length); // warning CS8602: dereference of a possibly null reference
if (nick != null)
Console.WriteLine(nick.Length); // no warning: the compiler knows it is not null here
static string? GetNickname() => null;The null-safe operators
| Operator | Name | Meaning | Example |
|---|---|---|---|
| ?. | null-conditional | Use the member only if not null; otherwise the result is null | name?.Length |
| ?? | null-coalescing | Use the left value, or the right one if the left is null | name ?? "Guest" |
| ??= | null-coalescing assignment | Assign only if the variable is null | city ??= "Unknown"; |
| ! | null-forgiving | Tell the compiler "trust me, not null" (no runtime check) | name!.Length |
string? input = Console.ReadLine();
int? len = input?.Length; // null if input is null
string display = input ?? "(nothing typed)";
string clean = input?.Trim() ?? ""; // combine them
string? city = null;
city ??= "Unknown";
Console.WriteLine(city); // UnknownChecking for null
string? email = GetEmail();
if (email is null) Console.WriteLine("No email");
if (email is not null) Console.WriteLine(email.ToLower());
if (string.IsNullOrWhiteSpace(email)) Console.WriteLine("Missing or blank");
static string? GetEmail() => " ";Common mistakes and fixes
- Ignoring CS8602 warnings: each one is a possible crash. Add a null check, use ?. and ??, or make sure the value is set.
- Reading .Value on an empty int?: throws. Use ?? or GetValueOrDefault() instead.
- Returning null for "no items": return an empty array or list instead, so callers can loop without checks.
- Using ! everywhere to quieten the compiler: it hides real bugs. Fix the cause.
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
null, nullable types and null-safe operators · 1/7
In this lesson you will learn about null and how to stop it crashing your programs.
Prefer a video by a teacher? Find free videos on “C# nullable reference types null conditional null coalescing operator” on YouTube ↗
In real life: An optional GSTIN on an invoice
Businesses have a GSTIN (GST identification number); individual customers usually do not. A billing app stores the GSTIN as string? and the delivery slot as an optional time, and prints sensible text when they are missing.
string customer = "Kumar Traders";
string? gstin = null; // not given
int? deliverySlotHour = 18;
Console.WriteLine($"Bill to: {customer}");
Console.WriteLine($"GSTIN: {gstin ?? "Not registered"}");
Console.WriteLine($"GSTIN length: {gstin?.Length ?? 0}");
Console.WriteLine(deliverySlotHour is int h ? $"Delivery at {h}:00" : "Delivery: any time");Practice (0/4 done)
string? s = null; What is s ?? "none"?
string? s = null; What is s?.Length?
int? x = null; What happens with int y = x.Value;?
Write a method Greeting(string? name, int? age) that returns: "Hello, Guest" when name is null or blank, otherwise "Hello, <trimmed name>", followed by " (age unknown)" when age is null or " (<age>)" otherwise. Do not use the ! operator.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Strings: methods, interpolation, verbatim and raw stringsArrays, strings and null · same module
- Arrays: one name, many valuesArrays, strings and null · same module
- Null safetyKotlin and Android App Development · Null safety, functions and lambdas
- Sound null safetyFlutter and Dart · Null safety and object-oriented Dart
- Classes and objectsJava Programming (Core to Spring Boot) · Classes and objects
- Structs, value types and reference typesClasses and objects
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
Which type can hold null?
Answer: int?
Value types need ? to become nullable.
With nullable reference types enabled, what does string? mean?
Answer: A string that may be null
The ? marks that null is an allowed value.
Do nullable-reference-type warnings change how the program runs?
Answer: No, they are compile-time warnings only
They are static analysis warnings; runtime behaviour is the same.
string? c = null; c ??= "Pune"; c ??= "Delhi"; What is c?
Answer: Pune
The first ??= assigns Pune. The second does nothing because c is no longer null.
Which exception do you get for name.Length when name is null?
Answer: NullReferenceException
Accessing a member through a null reference throws NullReferenceException.
What is the type of name?.length when name is String??Related
What is "sound" null safety?Related
Answer: If a type is non-nullable, the value can never be null at run time
The guarantee is enforced by the compiler.
From Sound null safety
What is the default value of an uninitialised String field?Related
Answer: null
Object fields default to null (unlike local variables, which have no default).
From Classes and objects
What is the default value of a reference-type field?Related
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- This is the last topic of “Arrays, strings and null”. The module exam comes next.
- Module 3 exam: Arrays, strings and null · 13 questions · 20 min, without help. 4 topics of this module still to finish first.
- Then the next module, Classes and objects. 43 topics left in the course before the final exam.