These questions are follow up to the question i asked earlier about Extension Methods.
Last Updated : 01 May, 2019 In C#, the extension method concept allows you to add new methods in the existing class or in the structure without modifying the source code of the original type and you do not require any kind of special permission from the original type and there is no need to re-compile the original type. It is introduced in C# 3.0.
Extension methods are methods that can extend existing types without the need to inherit from a class and creating your own custom logic. It can also be applied to interfaces. Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling the derived type or otherwise modifying the original type.
The main advantage of the extension method is to add new methods in the existing class without using inheritance. You can add new methods in the existing class without modifying the source code of the existing class. It can also work with sealed class.
Let us understand C# Extension Methods with an example. Create a console application and then add a class file with the name OldClass.cs and then copy and paste the following code in it.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With