LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 4115 min read

Nullable Types

Learn nullable value types, nullable reference types, and how C# helps you avoid null reference exceptions.

The Problem with Null

A `NullReferenceException` — trying to use an object that doesn't actually exist — is one of the most common runtime errors in any C-family language. Modern C# gives you compiler help to catch these mistakes before they happen.

Nullable Value Types

Value types like `int` can't normally be null — appending `?` makes them nullable.

int? age = null;
if (age.HasValue)
{
Console.WriteLine(age.Value);
}
else
{
Console.WriteLine("Age not provided.");
}
Output

Click Run to see what this code prints.

Nullable Reference Types

Since C# 8, when nullable reference types are enabled (the default in new projects), `string` means "never null," while `string?` explicitly allows null. The compiler warns you if you use a nullable value without checking it first.

string? middleName = null; // explicitly nullable
string firstName = "Amit"; // compiler expects this to never be null

Null-Conditional Operator

`?.` safely accesses a member only if the object isn't null, short-circuiting to null instead of throwing.

string? name = null;
int? length = name?.Length; // null, doesn't throw
Console.WriteLine(length ?? -1);
Output

Click Run to see what this code prints.

FAQs

It only produces warnings, not compile errors, so existing code keeps working — but new projects are strongly encouraged to fix the warnings as they go.

Summary

  • `int?` makes a value type nullable.
  • Nullable reference types make "can this be null?" part of the type system.
  • `?.` and `??` provide safe, concise ways to work with potentially-null values.
Next Lesson →

Records