WeCodeAcademy

C# Nullable Types and Null Handling

ExampleC#
using System;

class Program
{
    static void Main()
    {
        int? maybe = null;
        Console.WriteLine(maybe.HasValue);
        Console.WriteLine(maybe ?? -1);
        maybe = 7;
        Console.WriteLine(maybe.Value);

        string name = null;
        Console.WriteLine(name?.Length);
        Console.WriteLine(name?.Length ?? 0);
        name ??= "default";
        Console.WriteLine(name);

        string text = "42";
        if (int.TryParse(text, out int number))
        {
            Console.WriteLine(number + 1);
        }
        Console.WriteLine(int.TryParse("abc", out int bad));
    }
}
Output
False
-1
7

0
default
43
False

Printing a null value gives an empty line, which is why the fourth output is blank. ?. safely stops at null, and ?? supplies a fallback.

Quick check

What does name?.Length return when name is null?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.