C# / CHAPTER 13

Nullable values and explicit failures

Intermediate

Separate absent data, valid defaults, and exceptional failures.

By the end of this chapter

  • Use nullable value types
  • Choose a fallback with ??
  • Handle parsing without hiding errors

The idea

A nullable value type such as int? represents either an int or no value. The null-coalescing operator ?? supplies a fallback when the left operand is null. This is different from testing whether the stored number equals zero: zero can be valid data. Accessing Value without first ensuring a value exists can throw, so prefer patterns or explicit absence handling.

Parsing is another boundary where failure should remain visible. int.TryParse reports success separately from the resulting number, making it suitable for expected user-input mistakes. Exceptions are appropriate when a failing operation cannot supply its promised result, but catch only where there is a useful recovery or message. Do not silently turn every error into a valid-looking count.

C# example
using System;
int? stored = null;
int fallback = stored ?? 10;
Console.WriteLine(fallback);
if (int.TryParse("27", out int value))
  Console.WriteLine(value + 1);
Result
10
28

The absent stored value selects ten. Successful parsing writes twenty-seven to value, and the guarded branch prints twenty-eight.

Try it yourself

Return a nullable integer for a valid nonnegative count, using null for malformed or negative input.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

What is printed?
int? amount = 0;
Console.WriteLine(amount ?? 8);