Coder Perfect

In C#, the keyword “this” is used in formal parameters for static methods.

Problem

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

Solution #1

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();

rather than

MyClass myClass = new MyClass();
int i = Foo(myClass);

This enables the creation of fluid interfaces, as described below.

Answered by Preet Sangha

Solution #2

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

Solution #3

Apart from Preet Sangha’s explanation, Intellisense shows the extension methods with a blue arrow (for example, in front of “Aggregate>”):

You need a

using the.namespace.of.the.static.class.with.the.extension.methods;

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

Solution #4

Extension methods are what they are. Welcome to a whole new world of fluency. 🙂

Answered by JP Alioto

Solution #5

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