Menu
Coddy logo textTech

Nullable Value Types

Part of the Logic & Flow section of Coddy's C# journey — lesson 32 of 66.

In C#, value types like int, float, and bool cannot normally hold null values. Nullable value types allow these types to represent either a value or null.

Declare a regular int:

int regularNumber = 10;

Declare a nullable int using the ? syntax:

int? nullableNumber = 20;

Assign null to a nullable type:

nullableNumber = null;

After executing the above code, nullableNumber contains no value (null).

Check if a nullable type has a value:

if (nullableNumber.HasValue)
{
    Console.WriteLine("Value is: " + nullableNumber.Value);
}
else
{
    Console.WriteLine("No value");
}

You can also use the null-coalescing operator to provide a default value:

int definiteNumber = nullableNumber ?? 0;
challenge icon

Challenge

Easy

Create a method named ProcessNullableAge that:

  1. Takes a nullable int parameter called age
  2. Checks if the age has a value
  3. If it has a value, prints "Age is: X years" (where X is the value)
  4. If it doesn't have a value, prints "Age not provided"
  5. Returns the age value if present, otherwise returns 0

Cheat sheet

Nullable value types allow value types like int, float, and bool to represent either a value or null.

Declare a nullable type using the ? syntax:

int? nullableNumber = 20;
nullableNumber = null;

Check if a nullable type has a value using HasValue:

if (nullableNumber.HasValue)
{
    Console.WriteLine("Value is: " + nullableNumber.Value);
}
else
{
    Console.WriteLine("No value");
}

Use the null-coalescing operator ?? to provide a default value:

int definiteNumber = nullableNumber ?? 0;

Try it yourself

using System;

class Program
{
    // Implement the ProcessNullableAge method here
    
    static void Main(string[] args)
    {
        string input = Console.ReadLine();
        
        int? age = null;
        if (input != "null")
        {
            age = int.Parse(input);
        }
        
        int result = ProcessNullableAge(age);
        Console.WriteLine("Returned value: " + result);
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow