C sharp - Nullable Types

Nullable Types – Handling null with ? and ??

1. What is a Nullable Type?

  • By default, value types (int, double, bool, etc.) cannot be null.

    int x = null; // ❌ Error
    
  • Sometimes, you may want to allow a value type to represent “no value”.

  • That’s where nullable types come in.


2. Declaring Nullable Types

You make a value type nullable by adding ?.

int? age = null;    // Nullable int
bool? isActive = null;  // Nullable bool

They can hold either:

  • A normal value (e.g., 42), or

  • null.


3. Checking for Null

You can check with HasValue or compare directly to null:

int? number = null;

if (number.HasValue)
    Console.WriteLine($"Number is {number.Value}");
else
    Console.WriteLine("Number is null");

if (number != null)
    Console.WriteLine(number.Value);

4. Null-Coalescing Operator ??

  • Provides a default value if the nullable is null.

int? tickets = null;
int available = tickets ?? 0;  // If null, use 0
Console.WriteLine(available);  // Output: 0

5. Null-Coalescing Assignment ??= (C# 8+)

  • Assigns a value only if the variable is currently null.

int? count = null;
count ??= 10;   // count becomes 10
Console.WriteLine(count);

6. Nullable Reference Types (C# 8+)

  • By default, reference types (like string) can already be null.

  • Nullable reference types introduce compiler warnings to prevent NullReferenceException.

string? name = null;    // Nullable reference type
string nonNullable = "Hello"; // Cannot be null (compiler warning if you assign null)

This is mainly for better null safety in large projects.


7. Example Putting It All Together

class Program
{
    static void Main()
    {
        int? score = null;

        // Using ?? operator
        int finalScore = score ?? -1;  
        Console.WriteLine($"Final Score: {finalScore}"); // Output: -1

        // Using ??= operator
        score ??= 100;
        Console.WriteLine($"Score after assignment: {score}"); // Output: 100
    }
}

Summary

  • int? allows value types to hold null.

  • Use .HasValue or == null to check.

  • ?? provides a default value.

  • ??= assigns a value only if null.

  • Nullable reference types (C# 8+) help prevent NullReferenceException.