Nullable Value Types

Store "no value yet" in an int?, decimal? or bool?, check it with HasValue or null before you read it, and write an optional parameter that a call can leave out.

Apprentice · C# · Updated

By

After this lesson you can

  • Store a missing value in a nullable value type such as int?, and check it with HasValue or null before reading it
  • Write a method with an optional parameter, such as int? points = null, that a call can leave out

Key takeaways

  • An int always holds a number, so 0 can't mean "no value yet". An int? holds a number or null, which means no value at all.
  • The ? works the same way on decimal, double and bool. A bool? has three states, such as yes, no and "hasn't answered yet".
  • Check before you read. HasValue and != null are true when there's a number, and .Value reads it; .Value on null stops the program.
  • A parameter with a default value, such as int? points = null, is optional. A call can leave it out, and the method gets the default.
  • Optional parameters come after the required ones.

Real data has gaps. A game that hasn't been played has no score yet. A sign-up form has fields people leave blank. A product can be waiting for its price. Your programs need a way to say "there's no value here yet" that can't be mistaken for a real value. You'll use it in nearly every app that reads a form, and in every app that reads a database: later in the course, a database column that may be empty comes back to C# as exactly the kind of type this lesson teaches.

Zero isn't "no score yet"

The backyard basketball league keeps every team's points on its website. On Saturday morning, the Hawks have played their game and scored nothing (a bad day), and the Owls haven't played yet. An int has to hold a number, so both get a 0:

int hawksPoints = 0;   // played, and scored nothing
int owlsPoints = 0;    // hasn't played yet

Anyone reading the website sees two teams with 0 points. One of those numbers is a lie.

A common first fix is a "magic number" that means "not played": -1, say. It works until some code forgets about it. Here a season total adds up the Hawks' games, and the third game hasn't been played:

int[] hawksSeason = { 42, 38, -1 };   // -1 means "not played yet"
int total = 0;
foreach (int points in hawksSeason)
{
    total += points;
}
Console.WriteLine(quot;Season points: {total}");
Season points: 79

The Hawks scored 80 points, not 79. Every piece of code that ever touches the scores has to remember the -1, and one that doesn't gives a wrong answer with no error to warn you.

What the league needs is what a real scoreboard does before the game starts: it's blank. A blank says "nothing here yet"; a 0 says "we counted, and it came to nothing". C# has a word for the blank, null, which means no value at all. You met it in Understanding the String Class. But an int can't hold it:

int owlsPoints = null;
error CS0037: Cannot convert null to 'int' because it is a non-nullable value type

Two scoreboards side by side. The Hawks' board shows 0: they played and scored nothing. The Owls' board is blank: they haven't played yet, which is what null means.

int?: a number, or nothing

Put a ? after the type, and the variable can hold either a number or null. int? is read "nullable int", and it's called a nullable value type:

int? hawksPoints = 0;      // played, and scored nothing
int? owlsPoints = null;    // hasn't played yet

Console.WriteLine(quot;Hawks: {hawksPoints}");
Console.WriteLine(quot;Owls: {owlsPoints}");
Console.WriteLine(hawksPoints == null);
Console.WriteLine(owlsPoints == null);
Hawks: 0
Owls:
False
True
  • A null prints as nothing at all, which is why the Owls' line ends after the colon.
  • == null asks "is there no value?", and != null asks "is there a value?". The Hawks' 0 is a real value, so hawksPoints == null is False.

The ? works the same way on decimal, double and bool. A bool? is handy for a question someone hasn't answered yet, because it has three states: true, false and null.

decimal? ticketPrice = null;     // the league hasn't set a price yet
bool? mayaPlaysSaturday = null;  // Maya hasn't answered yet

Console.WriteLine(ticketPrice == null);
Console.WriteLine(mayaPlaysSaturday == null);

mayaPlaysSaturday = false;       // now she has: she can't make it
Console.WriteLine(mayaPlaysSaturday == null);
Console.WriteLine(mayaPlaysSaturday);
True
True
False
False

Maya's false is an answer ("no, I can't play"), and null is no answer at all. A plain bool couldn't tell the two apart.

Check before you read: HasValue and .Value

A nullable value type has two properties for getting at what's inside:

  • HasValue is true when there's a number and false when it's null. It means the same as != null.
  • .Value gives you the number itself, as a plain int.

You need .Value because an int? might be empty, and C# won't let you put a maybe-empty value where an int must go:

int? owlsPoints = null;
int total = owlsPoints;
error CS0266: Cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast?)

So check first, then read. Here's the season total again, with null for the game that hasn't been played:

int?[] hawksSeason = { 42, 38, null };
int total = 0;
int played = 0;

foreach (int? points in hawksSeason)
{
    if (points.HasValue)
    {
        total += points.Value;
        played++;
    }
}

Console.WriteLine(quot;{played} games played, {total} points");
2 games played, 80 points

int?[] is an array of nullable ints, so each game holds a score or null. Inside the if, points is sure to have a number, so points.Value is safe. if (points != null) would do the same job.

Reading .Value without checking works only while there's a value. On null, the program stops:

int? owlsPoints = null;
Console.WriteLine(owlsPoints.Value);
Unhandled exception. System.InvalidOperationException: Nullable object must have a value.

Optional parameters: a call can leave it out

The league's website shows a line for each team. After the game, the method gets the team and its points. Before the game, there are no points to pass. You could write two methods, but there's a neater way: give the parameter a default value, the value it gets when a call leaves it out. A parameter with a default value is an optional parameter.

Start with a default that's a plain value. A new player who isn't on a team yet goes on the waitlist:

Console.WriteLine(Welcome("Maya"));
Console.WriteLine(Welcome("Leo", "Hawks"));

string Welcome(string name, string team = "the waitlist")
{
    return quot;Welcome, {name}! You're on {team}.";
}
Welcome, Maya! You're on the waitlist.
Welcome, Leo! You're on Hawks.

Now the score line. Its default is null, so the method can tell "the call left the points out" from "the team scored 0":

Console.WriteLine(ScoreLine("Hawks", 42));
Console.WriteLine(ScoreLine("Owls", 0));
Console.WriteLine(ScoreLine("Bears"));

string ScoreLine(string team, int? points = null)
{
    if (points == null)
    {
        return quot;{team}: not played yet";
    }
    return quot;{team}: {points} points";
}
Hawks: 42 points
Owls: 0 points
Bears: not played yet
  • int? points = null reads "points, a nullable int, which is null when the call leaves it out".
  • ScoreLine("Bears") leaves the points out, so points is null.
  • A plain int points = 0 would also make the parameter optional, but then ScoreLine("Bears") and ScoreLine("Owls", 0) would look the same to the method. null keeps them apart.
  • Optional parameters come after the required ones. Put int? points = null first, and C# stops with error CS1737: Optional parameters must appear after all required parameters.

Do it: find a player's best game

The league's stats page shows each player's best game of the season: the most points they scored in one game. Games that haven't been played yet are null, and they must not count.

The method gets one value:

  • games: the player's points in each game of the season, an int?[]. A game not played yet is null ({ 12, null, 20, 7 }).

For example, with { 12, null, 20, 7 }:

Game Points Best so far
1 12 12
2 null: not played, skip it 12
3 20 20
4 7 20

So BestGame(new int?[] { 12, null, 20, 7 }) returns 20.

Your job: write the method int? BestGame(int?[] games).

  • Return the most points in one played game.
  • Skip every game that is null.
  • When no game has been played (every game is null, or the array is empty), return null.
  • A game of 0 points is a real game: { 0, null } returns 0, not null.

Practiced live on the lesson page: write the C# right there and check it.

Check yourself

2 questions to try on the lesson page.

So what

null is how a program says "there's nothing here yet", and an int? lets a number say it too, so a blank never gets mistaken for a 0 again.

Key terms

Cheat sheets