I’ve come across multiple examples of C# code, such as this:
public static int Foo(this MyClass arg)
In this example, I haven’t been able to find an explanation of what the this keyword implies. Do you have any ideas?
Asked by kpozin
This is a method of extension. An explanation can be found here.
it means that you can call
MyClass myClass = new MyClass(); int i = myClass.Foo();
MyClass myClass = new MyClass(); int i = Foo(myClass);
This enables the creation of fluid interfaces, as described below.
Answered by Preet Sangha
Scott Gu’s blog piece, which I’ve quoted, explains it well.
The following sentence in that piece, in my opinion, answers the question:
Answered by James Wiseman
Apart from Preet Sangha’s explanation, Intellisense shows the extension methods with a blue arrow (for example, in front of “Aggregate>”):
You need a
for the extension methods to appear and to be available, if they are in a different namespace than the code using them.
Answered by Olivier Jacot-Descombes
Extension methods are what they are. Welcome to a whole new world of fluency. 🙂
Answered by JP Alioto
This is something I just learned the other day: the this keyword indicates that a method is an extension of the preceding class. As a result, MyClass will have a new extension method called Foo (which takes no parameters and returns an int; it can be used like any other public method).
Answered by jpoh
Post is based on https://stackoverflow.com/questions/846766/use-of-this-keyword-in-formal-parameters-for-static-methods-in-c-sharp