What Advantages of Extension Methods have you found? [closed]
Solution 1:
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.
Solution 2:
I think extension methods help a lot when writing code, if you add extension methods to basic types you'll get them quicky in the intellisense.
I have a format provider to format a file size. To use it I need to write:
Console.WriteLine(String.Format(new FileSizeFormatProvider(), "{0:fs}", fileSize));
Creating an extension method I can write:
Console.WriteLine(fileSize.ToFileSize());
Cleaner and simpler.
Solution 3:
Don't forget tooling! When you add an extension method M on type Foo, you get 'M' in Foo's intellisense list (assuming the extension class is in-scope). This make 'M' much easier to find than MyClass.M(Foo,...).
At the end of the day, it's just syntactic sugar for elsewhere-static-methods, but like buying a house: 'location, location, location!' If it hangs on the type, people will find it!
Solution 4:
Two more benefits of extension methods that i have come across:
- A fluent interface can be encapsulated in a static class of extension methods, thereby achieving a separation of concerns between the core class and it's fluent extensions; I've seen that achieve greater maintainability.
- Extension methods can be hung off of interfaces, thereby allowing you to specify a contract (via an interface) and an associated series of interface-based behaviors (via extension methods), again offering a separation of concerns. An example are the Linq extension methods like
Select(...)
,Where(...)
, etc. Hung off theIEnumerable<T>
interface.