C# extension method gives us the illusion of adding an instance method on a 3rd party class.

While worked on adding extension methods to WEB API controller, I felt these extension methods cannot do too much without accessing controller’s instance methods. So I switched to inheritance. BaseApiController<T> was inherited from ApiController, and I also added template methods and function objects to achieve what I wanted to do.

So when do we use extension method and when do we use instance method?

Extension Method Instance Method
Inheritance No Yes
Add to base class without notice Yes No
Can access objects’ internals No Yes
Create a new type No Yes
Scope namespace with inheritance tree
Design pattern similarity Decorator (add new behavior with modifying the base class)
Extend sealed class Yes No

Another interesting observation is that in Javascript, we can add a method to an object directly to do the same thing without extension method and instance method. So in my personal opinion, JavaScript is more expressive than C# if we know what we are doing.

 

References:

  1. https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods
  2. https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/how-to-implement-and-call-a-custom-extension-method

 

Advertisements