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

C#ParametersThis

C# Problem Overview


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?

C# Solutions


Solution 1 - C#

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.

Solution 2 - C#

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.

Solution 3 - C#

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.

Solution 4 - C#

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

Solution 5 - C#

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

Solution 6 - C#

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

Solution 7 - C#

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionkpozinView Question on Stackoverflow
Solution 1 - C#Preet SanghaView Answer on Stackoverflow
Solution 2 - C#James WisemanView Answer on Stackoverflow
Solution 3 - C#Olivier Jacot-DescombesView Answer on Stackoverflow
Solution 4 - C#JP AliotoView Answer on Stackoverflow
Solution 5 - C#Dean PView Answer on Stackoverflow
Solution 6 - C#jpohView Answer on Stackoverflow
Solution 7 - C#dcarl661View Answer on Stackoverflow