Modern C# · Lesson 2

Nullable values

Represent an absent measurement without inventing a number.

How it works

An int? holds either an integer or null. The question mark changes what the variable can represent; it does not choose a fallback value. The null coalescing operator evaluates its right side only when the left side is null. Here the first display uses zero because no measurement exists. After assigning seven, the same expression displays seven. Keep the distinction between a real zero and a missing measurement in storage, even if a particular screen displays both similarly.

Calling Value on an empty nullable throws. Pattern matching lets you extract the value only in the branch where it exists.

Try assigning zero rather than null. Print HasValue for both cases and explain why an average might need to exclude missing measurements while retaining actual zeroes.

A working example

using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;

int? measurement = null;
Console.WriteLine(measurement ?? 0);
measurement = 7;
if (measurement is int value) Console.WriteLine(value);

Expected output

0
7
Try this
A display fallback is not necessarily the stored value.