Skip to content

Extension Methods

Question

Explain extension methods. Can an extension method be called on a variable that holds null?

Short interview answer

Extension methods are static methods called with instance-method syntax. They can be invoked on a null reference because the receiver is passed as an argument, but the method must handle null safely.

Detailed answer

An extension method does not modify the original type or gain access to its private state:

public static bool IsBlank(this string? value) =>
    string.IsNullOrWhiteSpace(value);

var blank = ((string?)null).IsBlank(); // Calls IsBlank(null).

The compiler rewrites the call to a static method with value as the first argument. A null receiver reaches the method; a dereference inside it still throws unless the method checks for null.

Sources