C# · Data

Nullable Types

null means “no value”. It is useful — a customer may have no middle name — but reading a property of null crashes your program. C# gives you tools to handle null safely.

Beginner 5 min Lesson 10 of 26Examples target C# 13 on .NET 9 unless stated otherwise.
0/26 in C#
On this page · 5 min · Beginner

In simple words#

A form field can be filled or left blank. Nullable types let a variable say “no value yet” (null) — like a blank answer — and the compiler reminds you to check before using it.

null
Means “no value”.
int?
An int that may also be null.
?? and ?.
Give a default, or safely skip when null.

Learning objectives#

  • Make value types nullable with ?
  • Use ?. , ?? and ??= to handle null
  • Understand nullable reference types and compiler warnings
  • Check for null with is null and is not null

Explanation#

Value types (int, decimal, bool, DateTime) normally cannot be null. Add ? to allow it: int? discount = null;. Use .HasValue and .Value, or simply compare to null.

Reference types (string, classes) can hold null. With nullable reference types (on by default in new projects), string means “never null” and string? means “may be null”. The compiler warns when you might use a null.

?. is the null-conditional operator: name?.Length returns null instead of crashing when name is null.

?? supplies a fallback: discount ?? 0. ??= assigns only if the variable is currently null.

Check with is null / is not null. They always do a real null check, even if a class overloads ==.

Syntax#

C# Illustrative
int? qty = null;
string? nickname = null;
int len = nickname?.Length ?? 0;
nickname ??= "Guest";
if (nickname is not null) { ... }

Code example: Missing data without crashes#

C#Program.cs Illustrative
int? discount = null;
Console.WriteLine(discount.HasValue);
Console.WriteLine(discount ?? 0);
discount = 15;
Console.WriteLine(discount.Value);


string? middleName = null;
Console.WriteLine(middleName?.Length ?? 0);
middleName ??= "N/A";
Console.WriteLine(middleName);


string? email = FindEmail(2);
if (email is not null)
{
    Console.WriteLine(email.ToUpper());
}
else
{
    Console.WriteLine("No email on file");
}


static string? FindEmail(int customerId) =>
    customerId == 1 ? "asha@example.com" : null;
Expected output
False
0
15
0
N/A
No email on file

This example is illustrative. Copy or download it and run it in your own environment; the expected output is shown above.

Step-by-step explanation#

  1. int? can hold null. HasValue is False until a number is assigned.
  2. discount ?? 0 uses 0 because discount is null.
  3. middleName?.Length is null (no crash), and ?? 0 turns it into 0.
  4. ??= assigns "N/A" because middleName was null.
  5. FindEmail returns string? to warn callers that the result may be missing; the is not null check handles both cases.

Real-world use case#

A customer table has optional columns such as DateOfBirth and MiddleName. EF Core maps them to DateTime? and string?, and the API uses ?? to send sensible defaults to the front end.

Common mistakes#

NullReferenceException

Calling customer.Address.City when Address is null crashes. Use customer.Address?.City or check for null first.

Reading .Value without checking

discount.Value throws InvalidOperationException when discount is null. Use ?? or HasValue.

Silencing warnings with !

name!.Length tells the compiler “trust me”. If you are wrong, it still crashes. Fix the logic instead.

Best practices#

  • Keep nullable reference types enabled (<Nullable>enable</Nullable>)
  • Return T? only when “no result” is a normal outcome
  • Use ?? to provide defaults at the edges of your code
  • Prefer is null over == null

Remember this#

int? = int that may be missing.

?. = “only if not null”. ?? = “otherwise use this”.

string? warns you; string promises a value.

Practice exercise#

Your task: Write a method GetDisplayName(string? nickname, string fullName) that returns the nickname when it is not null or empty, otherwise the full name.

Need a hint?
string.IsNullOrEmpty handles both null and "".
Show solution
C# Illustrative
Console.WriteLine(GetDisplayName(null, "Asha Rao"));   // Asha Rao
Console.WriteLine(GetDisplayName("Ash", "Asha Rao"));  // Ash


static string GetDisplayName(string? nickname, string fullName) =>
    string.IsNullOrEmpty(nickname) ? fullName : nickname;

Mini quiz#

Nullable Types quizPredict the output Question 1 of 3

What is printed?

string? s = null;
Console.WriteLine(s?.Length ?? -1);
Score so far: 0/0

Want more? Practise all C# MCQs · C# interview questions

My notes#

Saved in this browser.

Progress is saved in this browser. Sign in to sync.