Also remember that extension methods have been added as a way to help the Linq query be more readable when used in their C # style.
These 2 affectations are absolutely equivalent, but the first one is much more readable (and the gap in readability, of course, will widen with more methods).
int n1 = new List<int> {1,2,3}.Where(i => i % 2 != 0).Last(); int n2 = Enumerable.Last(Enumerable.Where(new List<int> {1,2,3}, i => i % 2 != 0));
Note that the full syntax should be:
int n1 = new List<int> {1,2,3}.Where<int>(i => i % 2 != 0).Last<int>(); int n2 = Enumerable.Last<int>(Enumerable.Where<int>(new List<int> {1,2,3}, i => i % 2 != 0));
Incidentally, parameters like Where and Last should not be explicitly specified, since they can be inferred due to the presence of the first parameter of these two methods (the parameter that is entered with the this and make them extension methods).
This point is obviously an advantage (among others) of extension methods, and you can take advantage of it in every such scenario in which a chain of methods is involved.
In particular, this is a more elegant and convincing way that I found a base class method called by any subclass and returning a strongly typed reference to this subclass (with the type of the subclass).
Example (well, this scenario is completely trashy): after a good night, the animal opens its eyes and then screams; each animal opens its eyes in the same way, while the dog barks and ducks.
public abstract class Animal { //some code common to all animals } public static class AnimalExtension { public static TAnimal OpenTheEyes<TAnimal>(this TAnimal animal) where TAnimal : Animal { //Some code to flutter one eyelashes and then open wide return animal; //returning a self reference to allow method chaining } } public class Dog : Animal { public void Bark() { /* ... */ } } public class Duck : Animal { public void Kwak() { /* ... */ } } class Program { static void Main(string[] args) { Dog Goofy = new Dog(); Duck Donald = new Duck(); Goofy.OpenTheEyes().Bark(); //*1 Donald.OpenTheEyes().Kwak(); //*2 } }
Conceptually, OpenTheEyes should be an Animal method, but then it should return an instance of the Abstract class Animal , which does not know the specific methods of the subclass, such as Bark or Duck or something else. 2 lines commented out as * 1 and * 2 will then raise a compilation error.
But thanks to extension methods, we can have a kind of "base method that knows the type of subclass on which it is called."
Note that a simple general method could do the job, but much more inconveniently:
public abstract class Animal {
This time, no parameters, and therefore impossible return type return. A call can be nothing more than:
Goofy.OpenTheEyes<Dog>().Bark(); Donald.OpenTheEyes<Duck>().Kwak();
... which can weigh a lot if more chain is involved (especially knowing that the type parameter will always be <Dog> on the Goofy line and <Duck> on the Donald one ...)