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

Viewed 158521

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?

7 Answers

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.

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

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).

Related