Advertisement
Beginner C#, Extension Methods

Why must extension methods be defined in a static class, and how does the compiler resolve a call to one?

Short answer

Extension methods are purely a COMPILE-TIME convenience — the compiler resolves 'obj.ExtensionMethod()' by rewriting it internally as 'StaticClass.ExtensionMethod(obj)', which requires the method to live in a static class; at runtime, there's no real difference from calling an…

Save C# mock interview
Advertisement
AModel answer
Extension methods are purely a COMPILE-TIME convenience — the compiler resolves 'obj.ExtensionMethod()' by rewriting it internally as 'StaticClass.ExtensionMethod(obj)', which requires the method to live in a static class; at runtime, there's no real difference from calling an ordinary static method.
public static class IntExtensions {
  public static bool IsEven(this int number) => number % 2 == 0;
}

int x = 4;
bool even = x.IsEven();          // syntactic sugar for:
bool even2 = IntExtensions.IsEven(x); // this equivalent static call
Real-world example
Understanding that extension methods don't actually modify the extended type at all — they're purely compiler-level syntactic sugar.
Likely follow-ups
  • Does this mean extension methods can access private members of the type they extend?
Related topics