Many of the BCL Classes have Methods and ExtensionMethods. What is the design decision to pick ExtensionMethods over Methods when Microsoft has the source code of their Class?
Thank you,
Smith
Many of the BCL Classes have Methods and ExtensionMethods. What is the design decision
Share
Actually most of the extension methods in the BCL apply not to classes, but to interfaces, which is a key power of extension methods.
For example, almost all of LINQ to objects is implemented as extensions to the
IEnumerable<T>interface, and not to the classesList<T>, HashSet<T>, etc.Because interfaces do not have functionality (just a contract), adding an extension method to a interface gives you a way to an interface itself. This is especially handy when the implementation need only know of the interface for it’s use and not implementation specifics (per se).
Microsoft does add new methods in their BCL classes all the time (though of course they avoid breaking changes wherever possible). But I believe the majority of their extension method use in the BCL is on interfaces and not for adding functionality that could easily be added with a new method directly to the class/struct.
So, in short, when Microsoft chooses to add functionality to a single
class(or family with a common base class), they’d probably just add the method directly (all things being equal), but if they wanted to apply a new method to all implementations of a given interface, they’d probably use an extension method on that interface.Also keep in mind this! Because Microsoft gave us extension methods, it applies to classes they didn’t create as well! For example, any class that you create that implements
IEnumerable<T>gets the functionality of LINQ as well as a bonus, even though you inherit no common base classes, etc.