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?
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'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.
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.