Quick Answer

Handle null parameter violations.

Understanding the Issue

This exception occurs when a method receives a null argument that it cannot handle.

The Problem

This code demonstrates the issue:

Csharp Error
public void Process(string input) {
    int length = input.Length; // Throws if null
}

The Solution

Here's the corrected code:

Csharp Fixed
// Explicit null check
public void Process(string input) {
    if (input == null) {
        throw new ArgumentNullException(nameof(input));
    }
    // Safe to use input
}

// C# 10 simplified null check
public void Process(string input!) { // Non-nullable
    // Compiler enforces non-null
}

// Nullable reference types (C# 8+)
#nullable enable
public void Process(string? input) {
    // Compiler warns about potential null
}

// ArgumentNullException.ThrowIfNull (C# 10+)
public void Process(string input) {
    ArgumentNullException.ThrowIfNull(input);
}

Key Takeaways

Validate null arguments and leverage C# nullability features.