kpozin
kpozin

Reputation: 26939

Use of "this" keyword in formal parameters for static methods in C#

I've come across several instances of C# code like the following:

public static int Foo(this MyClass arg)

I haven't been able to find an explanation of what the this keyword means in this case. Any insights?

Upvotes: 382

Views: 188082

Answers (7)

Dean P
Dean P

Reputation: 2225

Wouldn't it be convenient if you could neatly pop a List<>, that is, not only remove the first element, but return it aswell?

List<int> myList = new List<int>(1, 2, 3, 4, 5);

Without extension methods:

public static class ContainerHelper
{
    public static T PopList<T>(List<T> list)
    {
        T currentFirst = list[0];
        list.RemoveAt(0);
        return currentFirst;
    }
}

Calling this method:

int poppedItem = ContainerHelper.PopList(myList);

With extension methods:

public static class ContainerHelper
{
    public static T PopList<T>(this List<T> list)//Note the addition of 'this'
    {
        T currentFirst = list[0];
        list.RemoveAt(0);
        return currentFirst;
    }
}

Calling this method:

int poppedItem = myList.PopList();

Upvotes: 18

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112324

In addition to Preet Sangha's explanation:
Intellisense displays the extension methods with a blue arrow (e.g. in front of "Aggregate<>"):

enter image description here

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.

Upvotes: 12

dcarl661
dcarl661

Reputation: 322

"this" extends the next class in the parameter list

So in the method signature below "this" extends "String". Line is passed to the function as a normal argument to the method. public static string[] SplitCsvLine(this String line)

In the above example "this" class is extending the built in "String" class.

Upvotes: 1

Preet Sangha
Preet Sangha

Reputation: 65496

This is an extension method. See here for an explanation.

Extension methods allow developers to add new methods to the public contract of an existing CLR type, without having to sub-class it or recompile the original type. Extension Methods help blend the flexibility of "duck typing" support popular within dynamic languages today with the performance and compile-time validation of strongly-typed languages.

Extension Methods enable a variety of useful scenarios, and help make possible the really powerful LINQ query framework... .

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 allows the construction of fluent interfaces as stated below.

Upvotes: 348

Mutation Person
Mutation Person

Reputation: 30498

Scott Gu's quoted blog post explains it nicely.

For me, the answer to the question is in the following statement in that post:

Note how the static method above has a "this" keyword before the first parameter argument of type string. This tells the compiler that this particular Extension Method should be added to objects of type "string". Within the IsValidEmailAddress() method implementation I can then access all of the public properties/methods/events of the actual string instance that the method is being called on, and return true/false depending on whether it is a valid email or not.

Upvotes: 101

JP Alioto
JP Alioto

Reputation: 45117

They are extension methods. Welcome to a whole new fluent world. :)

Upvotes: 7

jpoh
jpoh

Reputation: 4586

I just learnt this myself the other day: the this keyword defines that method has being an extension of the class that proceeds it. So for your example, MyClass will have a new extension method called Foo (which doesn't accept any parameter and returns an int; it can be used as with any other public method).

Upvotes: 5

Related Questions