BuildQuill
C# learning path
13 of 25
Lesson 13 of 25
Lesson 13Beginner17 min

C# Null and Nullable Values

Represent missing data honestly, distinguish missing from empty or zero, and use nullable analysis and explicit defaults without hiding mistakes.

Before this lesson

  • Reference types
  • Conditions
  • Input and collections

Model the difference between absent and empty values

Use nullable value and reference types

Choose checks, defaults, and null-forgiving syntax responsibly

The short answer

null means that no value or object reference is present. It differs from 0, false, and an empty string. Nullable forms such as int? and string? state that absence is expected and force the program to handle that possibility deliberately.

01

Missing is a separate state

A survey score of 0 may mean the respondent chose the lowest score. If the respondent has not answered, storing 0 destroys that distinction. null represents the absence of a value, allowing the program to handle ‘not supplied’ separately from valid domain values.

The same distinction appears in text: an empty string means a string exists with no characters, whitespace contains characters that may display blank, and null means no string reference. Which states are valid depends on the domain rather than the type alone.

ValuePossible meaningSame as null?
0A real numeric valueNo
falseA real Boolean valueNo
""Present but empty textNo
nullNo value/reference presentYes
02

Nullable value types add an absence state

Value types such as int and DateTime normally always contain a value. Adding ? creates a nullable value type: int? can hold an integer or null. HasValue checks presence, Value retrieves the value but throws when absent, and GetValueOrDefault returns a fallback.

The ?? operator chooses a fallback only when the left side is null. A default is appropriate when the domain defines one. Using 0 for every missing number can quietly turn unknown data into a real measurement, so name or explain the policy.

C#
decimal? discount = null;
decimal appliedDiscount = discount ?? 0m;

Console.WriteLine(appliedDiscount);

Expected output

0
03

Nullable reference types are compiler analysis

In modern .NET projects with nullable reference types enabled, string means the code intends a non-null reference and string? means null is expected. The compiler tracks assignments and warns when a possible null is dereferenced. This feature improves design feedback; it does not make the runtime incapable of producing null.

The null-conditional operator ?. accesses a member only when the receiver is non-null and otherwise produces null. The null-forgiving operator ! silences a warning without adding a runtime check. Use ! only when you have evidence the compiler cannot see, not as a shortcut around unclear state.

C#
string? nickname = FindNickname();
int length = nickname?.Length ?? 0;

// FindNickname would be another method that may return null.
04

Remove impossible nulls at boundaries

If a customer must have a name, validate the input before creating the customer and store a non-null string afterward. Carrying string? through every later method forces the entire program to account for a state the domain says should not exist.

When absence is meaningful, keep it visible in the type and handle it close to the decision that understands what it means. A user interface may display Not provided; a calculation may skip the record; a required export may reject it. There is no universal fallback.

Good habits

  • Use string.IsNullOrWhiteSpace when blank and whitespace-only input are invalid.
  • Prefer a validated non-null model over scattered null checks.
  • Do not catch NullReferenceException as ordinary control flow; prevent the invalid dereference.

Quick knowledge check

Answer before you reveal.

01Is an empty string null?

No. It is a present string with zero characters.

02Does value! make a possible null non-null at runtime?

No. It only suppresses compiler analysis; dereferencing an actual null can still fail.

Practice challenge

Now build it without copying.

Model an optional delivery date with DateTime?. Print the formatted date when present and ‘Pickup only’ when absent. Then model a required customer name and reject blank input before using it.

You are done when

  • Absence is not represented by a fake date
  • The nullable value is checked before Value is read
  • The required name becomes non-blank after validation

Stretch: Use ?. and ?? to print the length of an optional note, then explain why a zero length is acceptable for the report even though null and empty remain different states.

Open challenge in playground

Lesson checkpoint

One small step locks it in

Mark this lesson complete, then keep the momentum going.

Complete and continue

Clear up the details

Frequently asked questions

Why does the browser compiler not show nullable reference warnings?

Its compiler configuration is older than a typical modern .NET project. The language model still matters when you move to a current SDK with nullable analysis enabled.

Should every reference type be nullable?

No. Use ? only when absence is a legitimate state. Non-null contracts reduce the number of cases every caller must handle.

What is NullReferenceException?

It occurs when code tries to access an instance member through a null reference. Trace where the absent reference entered the state and validate or model it earlier.