'this' Keyword in C#
This is what this
means
this
is a common keyword that shows up in different programming languages, and sometimes the differences are subtle (and confusing!).
In C#, this
can be referring to two different things, depending on the context in which it’s used.
this
in a class
If you see this
referenced in a class, chances are that it is a reference to the instance of the class. As an example:
class ThisKeyword
{
public string MyFavoriteColor { get; set; } = "green";
void AFunction()
{
var capture = this.MyFavoriteColor;
}
}
In the above example, the capture
variable will equal “green”. You are not required to use the this
keyword here, it is implied. However, if you have a naming conflict in your class, you will be required to use it. Consider the following example:
class ThisKeyword
{
public string MyFavoriteColor { get; set; } = "green";
public void Test()
{
var MyFavoriteColor = "blue";
//This will write out "blue".
Console.WriteLine(MyFavoriteColor);
//This will write out "green".
Console.WriteLine(this.MyFavoriteColor);
Console.ReadKey();
}
}
this
in extension methods
There is another place that you’ll see the this
keyword popup in C# – extension methods. Extension methods are a form of monkey patching. Consider the following example:
class ThisKeyword
{
public void APublicMethod()
{
//something
}
}
static class ThisKeywordExtensions
{
public static void ExtensionMethod(this ThisKeyword instance)
{
instance.APublicMethod();
}
}
In the above example, this
refers to the instance of ThisKeyword
that is being “monkey patched” with the extension method.