Search⌘ K
AI Features

Null Value

Explore how to handle null values effectively in C# by managing nullable reference and value types. Learn to use null checks, the null-coalescing operator, and the null-conditional operator to prevent runtime errors and write safer code.

In C#, we have a special value called null. This value represents the absence of a value. Understanding how to manage this state is essential for writing robust and error-free applications.

The null and reference types

In modern C#, reference types are non-nullable by default. We must explicitly indicate if a variable can hold a null value by adding a ? to the type. This syntax mimics how we handle nullable value types.

string? name = null;

We declare a variable name of type string?. The ? indicates that this reference type can accept null. We assign null to it, meaning it currently points to nothing in memory.

Assigning null to a non-nullable type, such as string, triggers a compiler warning to help prevent runtime errors.

Visualizing null in the memory
Visualizing null in the memory

If we try to access a member (like a method or property) of a variable that is currently null, the runtime throws a NullReferenceException.

C# 14.0
string? name = null;
// name is null. Accessing its members will yield an error
string nameInUpperCase = name.ToUpper();
Console.WriteLine(nameInUpperCase);
  • Line 1: We initialize name as null.

  • Line 4: We attempt to call the .ToUpper() method on name. Since name is null, the runtime throws a NullReferenceException. ...

The null and value types