Extension method

from Wikipedia, the free encyclopedia
QS IT
This article was due to content flaws on the quality assurance side of the computer science editorial added. This is done in order to bring the quality of the articles from the subject area of ​​computer science to an acceptable level. Help to eliminate the shortcomings in this article and take part in the discussion !  ( + )

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

Web links