skip to content

In C#, why does calling a string extension method such as IsNullOrBlank on a null reference not throw NullReferenceException at the call?

level: middleimportance: should knowfreq 45%

answer

  1. the receiver is just an argument
  2. no target object needed
  3. the exception moves inside the method
  4. this string? plus a guard

basics

~20 s

An extension call compiles to a static call that passes the receiver as an ordinary argument, so a null receiver simply arrives as null. Nothing throws at the call; the method body decides whether to accept null or throw.

solid answer

~40 s

`nickname.IsNullOrBlank()` compiles to `StringExtensions.IsNullOrBlank(nickname)`. A static call needs no target object, so the runtime has nothing to null-check, unlike an instance call, which throws `NullReferenceException` before the method body even runs. That makes null the extension's responsibility. A method designed for null, like `IsNullOrBlank(this string? text)`, simply handles it, and `[NotNullWhen(false)]` tells flow analysis the value is non-null when it returns false. A method that needs a value should declare `this string text` and guard with `ArgumentNullException.ThrowIfNull(text)`; otherwise the `NullReferenceException` surfaces from inside the extension, one frame away from the real mistake. With nullable reference types on, passing a maybe-null receiver to a non-nullable `this` parameter raises warning CS8604.

code

csharp · 31 lines
csharp
using System.Diagnostics.CodeAnalysis;
using Shared.Text;

string? nickname = null;
Console.WriteLine(nickname.IsNullOrBlank());          // True: a static call, no null check at the call
Console.WriteLine(nickname?.IsNullOrBlank() ?? true);  // ?. skips the call; result is bool?
if (!nickname.IsNullOrBlank())
    Console.WriteLine(nickname.Length);               // no CS8602 thanks to [NotNullWhen(false)]
try
{
    Console.WriteLine(nickname.Initial());
}
catch (ArgumentNullException ex)
{
    Console.WriteLine($"{ex.GetType().Name}: {ex.ParamName}");
}

namespace Shared.Text
{
    public static class StringExtensions
    {
        public static bool IsNullOrBlank([NotNullWhen(false)] this string? text) =>
            string.IsNullOrWhiteSpace(text);

        public static char Initial(this string text)
        {
            ArgumentNullException.ThrowIfNull(text);
            return text[0];
        }
    }
}

go deeper

for a junior

Know that an extension call on a null reference does not throw by itself; the receiver arrives as an ordinary argument.

for a middle

Explain the static call behind it, contrast it with an instance call on null, and show the bool? result of ?. in front of the helper.

for a senior

Set the null contract of each helper: nullable receiver plus NotNullWhen for tolerant ones, a non-nullable receiver and ThrowIfNull for the rest.

for a principal

Make the null contract of shared extension libraries a review rule, so stack traces point at callers instead of library internals.

## The receiver is just an argument An **extension method** is a static method whose first parameter is marked `this`. The compiler rewrites `nickname.IsNullOrBlank()` into `StringExtensions.IsNullOrBlank(nickname)`: the expression before the dot becomes the first **argument**. That is the whole explanation of the behaviour: - An **instance call** needs a target object. If the receiver is null, the runtime throws `NullReferenceException` **at the call**, before the method body runs, even for a non-virtual method that never touches `this`. - A **static call** has no target. Passing `null` as an argument is legal, so the call succeeds and the method starts running with its `this` parameter set to `null`. So calling an extension method on a null receiver is fine at compile time and at the call itself; what happens next is entirely up to the extension's body. ## Two kinds of extension, two contracts | Declaration | Meant for null? | What a null receiver does | |---|---|---| | `IsNullOrBlank(this string? text)` returning `string.IsNullOrWhiteSpace(text)` | yes | returns `true` | | `Initial(this string text)` with `ArgumentNullException.ThrowIfNull(text)` | no | throws `ArgumentNullException` naming `text` | | `Shout(this string text)` returning `text.ToUpperInvariant()` | no, unguarded | throws `NullReferenceException` from inside `Shout` | The first row is the legitimate use: a helper whose **name** says it tolerates null, mirroring `string.IsNullOrWhiteSpace`. The last row is the trap: the stack trace's top frame is the extension, not the caller that passed null, and a reader may assume the bug is in the shared library. ## Telling the compiler about the contract With **nullable reference types** enabled (the new-project templates and file-based apps turn them on), the receiver is checked like any argument: 1. Declare the receiver `string?` when null is a valid input; callers get no warning. 2. Add `[NotNullWhen(false)]` to that parameter when a `false` result proves the value is non-null; then `if (!nickname.IsNullOrBlank()) Console.WriteLine(nickname.Length);` compiles without a CS8602 dereference warning. 3. Declare the receiver `string` when a value is required; a caller passing a maybe-null receiver gets **warning CS8604**, "Possible null reference argument for parameter 'text'". The annotations are compile-time only. At run time a null still arrives if a caller ignores the warning, which is why a non-nullable receiver should still be guarded. ## The null-conditional operator changes the result type Writing `nickname?.IsNullOrBlank()` does something different from `nickname.IsNullOrBlank()`: - `?.` evaluates the receiver, and if it is null it **skips the call entirely**; - the expression's type becomes `bool?`, and its value is `null`, not `true`. So `nickname?.IsNullOrBlank() ?? true` is needed to get the same answer, and a reviewer should question `?.` in front of a helper that already handles null: it hides the helper's own logic and widens the type. ## Guarding the extensions that need a value For a library of string and sequence helpers, a consistent rule keeps callers out of trouble: - Name null-tolerant helpers so the tolerance is obvious (`IsNullOrBlank`, `OrEmpty`), and annotate them. - Give every other helper a non-nullable receiver and a first-line guard such as `ArgumentNullException.ThrowIfNull(text)`, so the exception names the parameter and points at the caller's mistake. - Do not rely on "it will throw anyway" for sequences: an iterator-based extension may not run its body until enumeration, so an unguarded null can surface much later. C# 14 extension properties behave the same way: `missing.Slug` on a null `string?` calls the generated static accessor, and the property body decides what to return. ## Reading the stack trace When an unguarded extension dereferences a null receiver, the top frame of the `NullReferenceException` is the extension method, for example `at E.Shout(String text)`, and the caller that passed null is the frame below it. Contrast an instance call on null: the exception is raised in the caller's frame, because the method was never entered. Knowing this difference tells you where to look first: with an extension in the top frame, the bug is usually the argument the caller supplied, not the helper. ## Mistakes to avoid - Assuming every member-access on null throws at that line. - Writing extensions that silently accept null without saying so in the name or the annotation. - Leaving a non-nullable receiver unguarded and debugging a `NullReferenceException` that points into the helper.

  • Where does the exception surface if an unguarded extension dereferences a null receiver?
    Inside the extension. `Shout(this string text) => text.ToUpperInvariant()` throws `NullReferenceException` with the extension as the top stack frame, and the caller that passed null appears one frame below. A first-line `ArgumentNullException.ThrowIfNull(text)` turns that into an exception that names the parameter.
  • What does nickname?.IsNullOrBlank() return when nickname is null?
    `null`, typed `bool?`. The null-conditional operator skips the call when the receiver is null, so the helper's own null handling never runs. You would need `?? true` to recover the helper's answer, which is a sign the `?.` was unnecessary.
  • Is it good practice for an extension method to accept a null receiver?
    Only when the method exists for that purpose and says so, as `IsNullOrBlank` does, with a nullable receiver and a flow attribute. Otherwise a non-nullable receiver plus a guard keeps the contract of an ordinary method, so readers are not surprised either way.

  • Calling any method on a null reference throws NullReferenceException at that line.
  • The runtime null-checks the receiver before an extension method runs.
  • nickname?.IsNullOrBlank() returns true when nickname is null.
  • Nullable annotations on the receiver stop null from arriving at run time.
  • An unguarded extension is fine because it will throw at the call anyway.