358

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?

kpozin
  • 25,691
  • 19
  • 57
  • 76
  • 11
    In addition to the accepted answer, for C# Extension Methods one must check out official [MSDN documentation](http://msdn.microsoft.com/en-us/library/bb383977.aspx). – vulcan raven Jan 16 '12 at 11:42
  • 5
    Extension methods are convenient but we must use caution when creating/using them - they can break! Quote from the General Guidelines in the [official MSDN documentation](https://msdn.microsoft.com/en-us/library/bb383977.aspx): "In general, we recommend that you implement extension methods sparingly and only when you have to. ... When using an extension method to extend a type whose source code you cannot change, you run the risk that a change in the implementation of the type will cause your extension method to break." – Krishna Gupta Jul 21 '15 at 22:57
  • Does that mean [this](https://pastebin.com/j3i209Dx) would be possible? Because that's what i'm looking for. – mekb Jul 21 '19 at 13:33

8 Answers8

336

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.

Preet Sangha
  • 64,563
  • 18
  • 145
  • 216
  • sub-classing is hard – Gerry Mar 07 '19 at 16:42
  • @Gerry - what do you mean? – Preet Sangha Mar 15 '19 at 23:29
  • 26
    Sorry, a little sarcasm - a lot of syntax these days seem to solve problems I didn't even know were problems. Readability should be a very high priority. – Gerry Mar 19 '19 at 14:44
  • 7
    To be honest @Gerry, it kind of sounds like you're in a classic [Blub Paradox](https://wiki.c2.com/?BlubParadox). A lot of syntax these days solves problems you're not having because you didn't know there was a better way, or you're not doing the kind of task that this syntax is awesome for. Most comments about '_this is a solution in search of a problem_' are actually an example of '_I don't know how that feature works, so it must be useless_'. – Myrddin Emrys Apr 28 '20 at 20:02
95

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.

James Wiseman
  • 29,946
  • 17
  • 95
  • 158
  • 22
    This should be the accepted answer. It's the only answer that actually explains what the actual purpose of the `this` keyword in the method signature is. The other answers only unhelpfully say "it's an extension method." I never fully understood how extension methods "attach" to the types they extend until reading this answer. Thank you! – Lews Therin Jul 19 '18 at 14:08
14

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();
Dean P
  • 1,841
  • 23
  • 23
12

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.

Jessica
  • 1,621
  • 2
  • 18
  • 34
Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
7

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

Community
  • 1
  • 1
JP Alioto
  • 44,864
  • 6
  • 88
  • 112
5

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

jpoh
  • 4,536
  • 4
  • 35
  • 60
1

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

dcarl661
  • 177
  • 3
  • 9
-1

The usage of modifier this before a parameter, is about extension method.

For more detailed explanation and example, see my CSDN blog.

http://t.csdn.cn/QYeW6

  • Good practices is to share next to a link, also the content / summary. A external link can be changed or can be deleted. – KargWare Aug 01 '23 at 03:18