What are extension methods?
This method allows us to add a new static method to the existing classes.
static void Main(string args)
int x = 3;
public static class MyMathExtension
public static int factorial(this int x)
if (x <= 1) return 1;
if (x == 2) return 2;
return x * factorial(x – 1);
Use Of This
- Extension methods allow existing classes to be extended without relying on inheritance or having to change the class’s source code.
- If the class is sealed than there in no concept of extending its functionality. For this a new concept is introduced i.e. extension methods.
- This feature is important for all developers especially if you would like to use the dynamism of the C# enhancements to be taken place in your classes design.
Important points while using extension methods:
- An extension method must be defined in a top-level static class.
- An extension method with the same name and signature as an instance method will not be called.
- Extension methods cannot be used to override existing methods.
- The concept of extension methods cannot be applied to fields, properties or events.
- Overuse of extension methods is not good style of programming.