These questions are follow up to the question i a
They make sense when you are using LINQ and want to chain or pipe functional output from one function to another. It improves the readability of the code and allows you to express a concept more elegantly (whatever that is worth).
They also allow you to give the appearance of instance methods on any type you like without modifying the source of that type, this can often help readability and the expressiveness of your code when it is used reasonably
Note that an extension method call like:
instance.SomeExtensionMethod()
gets compiled to:
StaticExtensionMethodClass.SomeExtensionMethod(instance);
so performance will be the same as any other static method call.
From my answer here:
As regards a practical use for Extension Methods, you might add new methods to a class without deriving a new class.
Take a look at the following example:
public class extended {
public int sum() {
return 7+3+2;
}
}
public static class extending {
public static float average(this extended extnd) {
return extnd.sum() / 3;
}
}
As you see, the class Extending
is adding a method named average to class Extended
. To get the average, you call average
method, as it belongs to extended
class:
extended ex = new extended();
Console.WriteLine(ex.average());
Reference: http://aspguy.wordpress.com/2008/07/03/a-practical-use-of-serialization-and-extension-methods-in-c-30/
As regards Performance, I think you can see an improvement with Extension methods since they are never dispatched dynamically, but it all depends on how the dynamic method is implemented.
Another interesting use of extension methods is when you would like to have certain functionality added to a class under one namespace but not another. One specific example is adding methods to ease unit testing - you wouldn't want them cluttering your production assemblies, but they're great to have when writing unit tests.