CodeBlanks Logo Icon CodeBlanks

String basics

C# course · Beginner · Lesson 16/116

Learn to store text with string and use escape sequences.

Nullable types

Sometimes a number variable needs to be empty. An int cannot hold null, but int? can. The question mark adds nullability to the type.

Example: int? count = null; The value of count is either a whole number or null. The HasValue property tells you if there is a value; Value returns it.

Nullable types are useful for representing 'no value' from a database or external source.

The ?? operator

The ?? operator (null coalescing) gives a default value when a reference or nullable value is null.

Example: int n = count ?? 0; If count is null, n becomes zero; otherwise the value of count is used. This turns a long if check into a short expression.

The right side is used only when the left side is null. It is a clean way to supply defaults when reading settings.

Exercise Print a default from a nullable

Assign null to an int? count variable. Write int total = count ?? 10; to get a default value. Then print total with Console.WriteLine.

Show example solution
int? count = null; int total = count ?? 10; Console.WriteLine(total);
Example solution:
using System;
class Program {
    static void Main() {
        int? count = null;
        int total = count ?? 10;
        Console.WriteLine(total);
    }
}

Test yourself

  1. Assign null to an int?

    int? count = ____;
    Show answer
    int? count = null;
  2. What is the value of n when count is null?

    int? count = null;
    int n = count ?? 5;
    • 0
    • null
    • throws
    • 5
    Show answer

    5 — Correct! count is null, so ?? returns the right side (5).

  3. Match each ?? expression to its result

    null ?? 5
    5
    3 ?? 5
    3
    null ?? 0
    0
    (int?)null ?? 7
    7

All lessons in Beginner