Glossary / Extension methods
Extension methods
An extension method is a static method that can be called with instance-method syntax on a receiver when the method is in scope. It adds a convenient API surface without modifying or inheriting from the extended type; it is resolved statically by the compiler, subject to namespace imports and overload rules.
Declaration and binding
Traditional extension methods are static methods in a non-nested, non-generic static class, with this on the first parameter. C# 14 introduces extension members that broaden the syntax; traditional extension methods remain common and widely compatible.
public static class StringExtensions
{
public static bool HasText(this string? value) =>
!string.IsNullOrWhiteSpace(value);
}
Call value.HasText() when the containing namespace is imported. If an applicable instance method exists, it takes precedence over extension candidates. Extension methods cannot access private members of the extended type and do not participate in virtual dispatch. They can be invoked as ordinary static methods too. Null receivers can be passed to extension methods, so code should decide whether to handle or reject null.
API guidance
Use extensions for cohesive, stateless operations that read well on the receiver. Avoid broad namespaces full of competing methods, surprising side effects, or names that shadow instance APIs. Generic extensions can infer type arguments but may produce overload ambiguity. For new C# 14 extension members, check compiler and target ecosystem support before relying on them in libraries.
Interview questions
- Do extension methods modify the original type? No; they are static methods presented with instance syntax.
- Which wins: instance or extension method? An applicable instance member takes precedence.
- Are they virtual? No.
- Can an extension method access private state? No.
- What changed in C# 14? Extension members add broader extension syntax, while traditional extension methods remain supported.