0

I found a method declared like this:

public static int WordCount(this string str)
{
    return str.Length;
}

What's the this keyword in this particular context?

It'sNotALie.
  • 22,289
  • 12
  • 68
  • 103
Joe
  • 25
  • 2
  • 2
    This must be a duplicate. – Brian Rasmussen Aug 19 '13 at 18:20
  • 1
    @BrianRasmussen [It is](http://stackoverflow.com/questions/846766/use-of-this-keyword-in-formal-parameters-for-static-methods-in-c-sharp). – It'sNotALie. Aug 19 '13 at 18:21
  • [search for question](https://www.google.ca/search?q=What+does+the+this+keyword+in+a+method+declaration+mean%3F&oq=What+does+the+this+keyword+in+a+method+declaration+mean%3F&aqs=chrome.0.69i57&sourceid=chrome&ie=UTF-8) title and go to the first link – Habib Aug 19 '13 at 18:23

2 Answers2

2

It's an extension method. Extension methods allow you to extend a type. It's great for types like string for which you don't have access to the source code.

With the example you provided, instead of calling

string test = "foo";
var result = StaticClass.WordCount(test);

You could use it as follows:

string test = "foo";
var result = test.WordCount();

Trivia: LINQ is implemented using extension methods, and in fact was the primary reason extension methods were added to the .NET framework.

Daniel Mann
  • 57,011
  • 13
  • 100
  • 120
0

It makes it an extension method.

What this means is that you can call the method like this:

arg.WordCount();

instead of like this:

Class.WordCount(arg);

It's mainly used for extending types (hence the name) that you can't directly modify the source code of.

It'sNotALie.
  • 22,289
  • 12
  • 68
  • 103