Do extension methods follow the object-oriented paradigm in C#?
Is it a good practice to use extension methods?
In the software development lifecycle how should we consider this question in the design phase?
Eric Lippert has blogged about this and I suspect I can't do much better than to quote him:
So, yes, the oft-heard criticism that "extension methods are not object-oriented" is entirely correct, but also rather irrelevant. Extension methods certainly are not object-oriented. They put the code that manipulates the data far away from the code that declares the data, they cannot break encapsulation and talk to the private state of the objects they appear to be methods on, they do not play well with inheritance, and so on. They're procedural programming in a convenient object-oriented dress.
They're also incredibly convenient and make LINQ possible, which is why we added them. The fact that they do not conform to some philosophical ideal of what makes an object-oriented language was not really much of a factor in that decision.
I would add, however, that they're useful beyond just LINQ - for the same reason that they're useful in LINQ. It's really nice to be able to express algorithms which work on arbitrary implementations of a particular interface (such as IEnumerable<T>
in LINQ to Obhects). Such algorithms typically don't have any context beyond the interfaces you're working on, so they're often naturally static.
If you accept that you've got some static utility method, which syntax would you rather use?
// Traditional
CollectionUtils.Sort(collection);
// Extension methods
collection.Sort();
The latter is simply more readable in my opinion. It concisely expresses what you want to do. It doesn't make it clear how you want to do it, but that's less important for most of the time - and more important when you're debugging that particular line, of course.
Extension methods are not an object oriented language feature. (compared to: classes, inheritance, polymorphism etc).
Like every language feature, it should be used where it is appropriate and for what it is designed for. There are already dozens of questions about when and how to use Extension methods.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With