Exception Handling
ArgumentNullException
C# Programming
Error Handling
.NET Development

Throwing ArgumentNullException

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

ArgumentNullException is the standard .NET signal that a caller passed null to a parameter that must not be null. Throwing it correctly makes APIs easier to debug, because the failure happens at the method boundary with the parameter name attached instead of deeper in the call stack as an unrelated NullReferenceException.

When to Throw It

Use ArgumentNullException when the problem is with an incoming argument. That means the method contract says a value is required, but the caller supplied null.

csharp
1public static string NormalizeName(string name)
2{
3    if (name is null)
4        throw new ArgumentNullException(nameof(name));
5
6    return name.Trim();
7}

This is better than allowing Trim() to throw later, because the exception clearly tells the caller which argument violated the contract.

Do not use ArgumentNullException for every null-related bug. If an internal field that should have been initialized is null, that is usually a state problem, not a bad argument from the caller. In that case a different exception or a design fix is appropriate.

Prefer ThrowIfNull in Modern .NET

In newer .NET versions, ArgumentNullException.ThrowIfNull is the most concise option.

csharp
1public sealed class MessageService
2{
3    private readonly ILogger _logger;
4
5    public MessageService(ILogger logger)
6    {
7        ArgumentNullException.ThrowIfNull(logger);
8        _logger = logger;
9    }
10
11    public void Send(string recipient, string message)
12    {
13        ArgumentNullException.ThrowIfNull(recipient);
14        ArgumentNullException.ThrowIfNull(message);
15
16        _logger.Log($"Sending message to {recipient}");
17    }
18}

This helper keeps the parameter name automatically and avoids repetitive if statements. It is especially useful in constructors and public methods where guard clauses are common.

If you target older frameworks, the classic explicit throw remains correct and readable.

Constructor Validation and Public APIs

Guard clauses matter most at boundaries: public methods, constructors, service entry points, controller actions, and library APIs. These are the places where invalid input should be rejected immediately.

For private helper methods, repeated null checks can become noise if the method is only called from already validated code. Validate once at the boundary and rely on that invariant internally unless there is a genuine reason to defend again.

A good exception message strategy is minimal and precise. The parameter name is usually enough. Only add a custom message when it helps explain a non-obvious rule.

csharp
1public static void SaveToFolder(string path)
2{
3    if (path is null)
4        throw new ArgumentNullException(nameof(path), "A destination path is required.");
5
6    // Save logic here.
7}

nameof Prevents Drift

Always use nameof(parameter) instead of a hard-coded string. Renaming a parameter later will keep the exception accurate.

csharp
1public static void ProcessOrder(Order order)
2{
3    if (order is null)
4        throw new ArgumentNullException(nameof(order));
5
6    // Processing logic here.
7}

This looks minor, but it prevents stale error messages during refactors and keeps diagnostics trustworthy.

Nullability Annotations Do Not Replace Guards

C# nullable reference types improve static analysis, but they do not remove the need for runtime validation at API boundaries. External callers, reflection, deserialization, and older code paths can still supply null. Treat compiler warnings as prevention and ArgumentNullException as enforcement.

That balance is what keeps library code robust. The compiler helps callers during development, while the runtime guard preserves a clear contract when values arrive from places the compiler cannot fully police.

Common Pitfalls

  • Throwing NullReferenceException manually instead of rejecting bad input with ArgumentNullException.
  • Using ArgumentNullException for internal object state problems that are not caused by caller input.
  • Hard-coding parameter names as strings instead of using nameof, which breaks during refactors.
  • Adding null checks everywhere, including private paths that already rely on validated invariants.
  • Waiting until a null value causes a later failure instead of validating at the method boundary.

Summary

  • Throw ArgumentNullException when a required method argument is null.
  • Fail early at public boundaries so callers get clear, actionable diagnostics.
  • Use ArgumentNullException.ThrowIfNull when targeting modern .NET.
  • Prefer nameof for parameter names to keep error messages correct after refactors.
  • Reserve other exception types for state errors or different contract violations.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.