Skip to content

Beginner · Arrays, strings and null · topic 13 of 43 · 30 min

null, nullable types and null-safe operators

Explanation

null means "no object here". Using a member of something that is null throws a NullReferenceException, one of the most common bugs. int? and other nullable value types can hold null, and nullable reference types (string? versus string) let the compiler warn you before null causes a crash. The operators ?. (call only if not null), ?? (use a fallback) and ??= (assign if null) keep code short and safe.

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.

csharp
string? middleName = null;
Console.WriteLine(middleName.Length);   // NullReferenceException at run time
The famous "Object reference not set to an instance of an object" error.
Think of it like this: null is like an empty envelope with no letter inside. Holding the envelope is fine. Trying to read the letter is where things go wrong. Good code checks whether there is a letter before reading.

Value 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.

csharp
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 null
int? is short for Nullable<int>. HasValue tells you if there is a value; .Value reads it (and throws InvalidOperationException if there is none).

Nullable 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.

csharp
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;
Treat these warnings seriously. Many teams turn warnings into errors so the build fails.

The null-safe operators

OperatorNameMeaningExample
?.null-conditionalUse the member only if not null; otherwise the result is nullname?.Length
??null-coalescingUse the left value, or the right one if the left is nullname ?? "Guest"
??=null-coalescing assignmentAssign only if the variable is nullcity ??= "Unknown";
!null-forgivingTell the compiler "trust me, not null" (no runtime check)name!.Length
csharp
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);                   // Unknown
These operators replace many if (x != null) checks.
Careful: The ! operator only silences the warning. If the value really is null, you still crash. Use it only when you truly know better than the compiler, not to make warnings go away.

Checking for null

csharp
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() => "  ";
is null and is not null are clear and always check for real null.

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.
Tip: A good habit: make things non-nullable by default, and add ? only where "no value" is a real, meaningful case.

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

null

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.

csharp
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");
Shows Bill to: Kumar Traders, GSTIN: Not registered, GSTIN length: 0, Delivery at 18:00.

Practice (0/4 done)

Task 1 · Question

string? s = null; What is s ?? "none"?

Task 2 · Question

string? s = null; What is s?.Length?

Task 3 · Question

int? x = null; What happens with int y = x.Value;?

Task 4 · Practice

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

Question 1

1.Which type can hold null?

Question 2

2.With nullable reference types enabled, what does string? mean?

Question 3

3.Do nullable-reference-type warnings change how the program runs?

Question 4

4.string? c = null; c ??= "Pune"; c ??= "Delhi"; What is c?

Question 5

5.Which exception do you get for name.Length when name is null?

Read more (free)

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

Answer: Int?

A safe call can produce null, so the result is nullable.

From Null safety

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

Answer: null

Reference-type fields default to null.

From Structs, value types and reference types

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

  1. This is the last topic of “Arrays, strings and null”. The module exam comes next.
  2. Module 3 exam: Arrays, strings and null · 13 questions · 20 min, without help. 4 topics of this module still to finish first.
  3. Then the next module, Classes and objects. 43 topics left in the course before the final exam.

← Previous: StringBuilder and string performance