I am facing this question regularly in interview. But I am not getting it's answer anywhere.Please help me.
-
3What about sealed classes? – Arturo Menchaca Mar 29 '16 at 14:33
-
Extension methods are syntactic sugar that were added to the language to make Linq calls look like they were built into all of the classes that implement `IEnumerable<>`, etc. That is, it's a way for you to "add" a method to a class that you don't have the source code for, or which is sealed. – Tony Vitabile Mar 29 '16 at 14:37
1 Answers
Inheritance and extension methods are entirely orthogonal. It's just a simple way of writing a function in C# using the familiar .
syntax. They only look similar if you use inheritance for code reuse, which tends to be frowned upon (but make sure you understand why - "best" practices are context-sensitive :)).
In any case, I'd expect the question is there to get you talking. Don't focus too hard on what the "right" answer is - just outline what inheritance is used for according to you, and what extension methods are used for, and what benefits and drawbacks each of those has. Get the dialog running.
For me, for example, extension methods are all about making common functions against an interface. That is, the functions add functionality on top of an interface (or class) while only using its public interface. This makes the "size" of the interface available to the function much smaller, which in turn makes it much easier to reason about.
Different people use extension methods differently, just like different people use inheritance differently. However, I find that as you shift from inheritance to composition, extension methods become more and more useful (and really, natural). Inheritance is a very specific technique that started being used for pretty much everything with little reason, but that's a big topic on Programmers.SE already anyway, just like the composition vs. inheritance debate :))

- 62,244
- 7
- 97
- 116