Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is so great about extension methods? [duplicate]

Possible Duplicate:
What Advantages of Extension Methods have you found?

All right, first of all, I realize this sounds controversial, but I don't mean to be confrontational. I am asking a serious question out of genuine curiosity (or maybe puzzlement is a better word).

Why were extension methods ever introduced to .NET? What benefit do they provide, aside from making things look nice (and by "nice" I mean "deceptively like instance methods")?

To me, any code that uses an extension method like this:

Thing initial = GetThing();
Thing manipulated = initial.SomeExtensionMethod();

is misleading, because it implies that SomeExtensionMethod is an instance member of Thing, which misleads developers into believing (at least as a gut feeling... you may deny it but I've definitely observed this) that (1) SomeExtensionMethod is probably implemented efficiently, and (2) since SomeExtensionMethod actually looks like it's part of the Thing class, surely it will remain valid if Thing is revised at some point in the future (as long as the author of Thing knows what he/she's doing).

But the fact is that extension methods don't have access to protected members or any of the internal workings of the class they're extending, so they're just as prone to breakage as any other static methods.

We all know that the above could easily be:

Thing initial = GetThing();
Thing manipulated = SomeNonExtensionMethod(initial);

To me, this seems a lot more, for lack of a better word, honest.

What am I missing? Why do extension methods exist?

like image 790
Dan Tao Avatar asked Nov 29 '22 20:11

Dan Tao


1 Answers

Extension methods were needed to make Linq work in the clean way that it does, with method chaining. If you have to use the "long" form, it causes the function calls and the parameters to become separated from each other, making the code very hard to read. Compare:

IEnumerable<int> r = list.Where(x => x > 10).Take(5)

versus

// What does the 5 do here?
IEnumerable<int> r = Enumerable.Take(Enumerable.Where(list, x => x > 10), 5);

Like anything, they can be abused, but extension methods are really useful when used properly.

like image 85
Mark Byers Avatar answered Dec 07 '22 00:12

Mark Byers