This is the syntax for declaring extension methods, a new feature in C # 3.0.
The extension method is part code, the magic part compiler, where the compiler, using intellisense in Visual Studio, shows that your extension method is actually available as an instance method for the object in question.
Let me give you an example.
There is no method in the String class called GobbleGobble, so create an extension method:
public static class StringExtensions { public static void GobbleGobble(this string s) { Console.Out.WriteLine("Gobble Gobble, " + s); } }
The class name is just my naming convention, there is no need to call it that, but it should be static, like the method.
After declaring the above method, you can enter the following in Visual Studio:
String s = "Turkey Baster!"; s.
after the period, wait for intellisense and note that there is a GobbleGobble method, execute the following code:
String s = "Turkey Baster!"; s.GobbleGobble();
It is important . The class in which the extension method is declared must be accessible to the intellisense compiler and processor so that intellisense displays this method. If you manually enter GobbleGobble and use the Ctrl + shortcut . , this will not help you get the correct use of directives in the file.
Note that the method parameter has disappeared. The compiler will silently navigate important bits that:
String s = "Turkey Baster!"; s.GobbleGobble(); ^ ^ | +
Thus, the above code will be converted by the compiler to the following:
String s = "Turkey Baster!"; StringExtensions.GobbleGobble(s);
So, during the call, there is nothing magical about this, it is just a call to the static method.
Please note that if your extension method declares more than one parameter, only the first one supports the this modifier, and the rest should be specified as part of the method call as usual:
public static void GobbleGobble(this string value, string extra) { | | ... | | } | | | | +--------------------------------------------+ | | | v | s.GobbleGobble("extra goes here"); | ^ | | | +-----------------------------------+
Extension methods were added in part because of Linq, where Linq C # syntax will look for suitable named extension methods for objects in the game, which means that you can "embed" Linq support in any type of class by simply declaring the correct extension methods. Of course, full Linq support is a lot of work, but it is possible.
In addition, the extension methods themselves are really useful, so read on it.
Here are some links: