mfs
mfs

Reputation: 4074

Why are LINQ operators defined as extension methods on IEnumerable interface and are not part of the interface itself? C#

So extension methods are used to add functionality to a class without a need to modify it's current code. I read that LINQ operators are defined that way.

My question is, when we know we want LINQ operators with every class that implements IEnumerable, why aren't LINQ operators defined directly in IEnumerable interface? Why use extension methods?

Thank you.

Upvotes: 4

Views: 177

Answers (1)

George Stocker
George Stocker

Reputation: 57907

The reason is three-fold:

  1. Changing the IEnumerable's interface is a breaking change for existing consumers. Since .NET 3.5 (When LINQ was introduced) wasn't the only version of .NET in production (at the time there .NET 2.0 and .NET 1.1), Microsoft's .NET team had to be particularly careful with changes.

  2. One fundamental part in architecting software is understanding the Object SOLID design principle "the Open-Closed" principle (the "O" in SOLID). Also known as Composition Over Inheritance. That is, when you are building software, prefer to have lego pieces that can work together to compose the lego result you want, not have a lego brick have all of that functionality built in to its inheritance chain. Not every lego brick needs the functionality of a lego wheel, but if you use inheritance every lego brick will have access to that functionality -- probably not what you want.

    By using composition and setting up the new extension method syntax; Microsoft could add on functionality to the Enumerable interface without worrying about existing consumers of IEnumerable, and none of those implementations would have to implement the entire set of LINQ operators, which they would have to do if it was baked in to the IEnumerable interface.

  3. IEnumerable and IEnumerable<T> were named simply: Provide an interface for a common way of iterating over a collection. That way everyone from hither to yon that needs to iterate over a collection can use this interface. If they start adding things to that interface that don't have to do with enumeration, the consumers will start to get confused. "What is this thing for again?"

    Another principle in software development is the Single Responsibility Principle (The S in SOLID), and when you have a class or interface that is responsible for two or things, it's time to revisit why that interface exists.

Upvotes: 7

Related Questions