October 08, 2014

“this” in function parameter

This is the syntax for declaring extension methods, a new feature of C# 3.0.
An extension method is part code, part compiler "magic", where the compiler with the help of intellisense in Visual Studio make it appear that your extension method is actually available as an instance method on the object in question.
Let me give an example.
There's no method on the String class that is named GobbleGobble, so let's 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, it isn't necessary to name it like that, but it has to be static, as do the method.

Reference: http://stackoverflow.com/questions/846766/use-of-this-keyword-in-formal-parameters-for-static-methods-in-c-sharp

No comments: