What Advantages of Extension Methods have you found?

Jerry picture Jerry · Jan 28, 2009 · Viewed 44.8k times · Source

A "non-believer" of C# was asking me what the purpose to extension methods was. I explained that you could then add new methods to objects that were already defined, especially when you don't own/control the source to the original object.

He brought up "Why not just add a method to your own class?" We've been going round and round (in a good way). My general response is that it is another tool in the toolbelt, and his response is it is a useless waste of a tool... but I thought I'd get a more "enlightened" answer.

What are some scenarios that you've used extension methods that you couldn't have (or shouldn't have) used a method added on to your own class?

Answer

Andrew Hare picture Andrew Hare · Jan 28, 2009

The only advantage of extension methods is code readability. That's it.

Extension methods allow you to do this:

foo.bar();

instead of this:

Util.bar(foo);

Now there are a lot of things in C# that are like this. In other words there are many features in C# that seem trivial and don't have great benefit in and of themselves. However once you begin combining these features together you begin to see something just a bit bigger than the sum of its parts. LINQ benefits greatly from extension methods as LINQ queries would be almost unreadable without them. LINQ would be possible without extension methods, but not practical.

Extension methods are a lot like C#'s partial classes. By themselves they are not very helpful and seem trivial. But when you start working with a class that needs generated code, partial classes start to make a lot more sense.