Extension method
As extension method (Engl. Extension method ) is under .NET , a method referred to a class expanded to be the extended class without being part of the implementation. It only looks like multiple inheritance at first glance . However , it is a matter of syntactic sugar , i.e. a compiler trick that assigns the extension method to the class.
application
Extension methods are defined in C # in a static class as a static method. The this keyword in front of the first parameter defines the type to be extended. This first parameter is not transferred with the call.
In the example, the System.String class is to be supplemented by another substring instruction:
public static class MyStringExtensions
{
public static string MySubstring(this string me, int position, int length)
{
//beliebige Logik
return "My" + me.Substring(position, length);
}
}
Use:
string teststring = "test";
teststring.MySubstring(1, 2);
advantages
- Extension of any classes, including "sealed" classes such as System.String
- Adding a specifically implemented method to an interface and thus to all classes based on it (e.g. IList)
- It is no longer necessary to derive entire classes to add your own features
disadvantage
- Extensions are made available through a Using directive. Namespace conflicts can arise here.
- Intensive use of extension methods can make the code confusing
literature
- Extension methods in the book Visual C # 2010 - The comprehensive manual by Andreas Kühnel, Rheinwerk Verlag , Bonn 2010, ISBN 978-3-8362-1552-7