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|
|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|