C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Static: This can not refer to a static field or method. It cannot occur inside a static class.
Tip: The "this" keyword is inferred by the compiler and not required. It is useful for expressing your intent.
Part 1: B is an instance method. The method B can be called as "this.B()" only if you are inside the class.
Part 2: The program accesses a field with "this". The statements "_a++" and "this._a++" are equivalent in this program.
C# program that uses this instance expression
using System;
class Perl
{
public Perl()
{
// Part 1: call instance method with "this."
this.B();
}
int _a; // Instance field
public void B()
{
// Part 2: increment instance field without "this."
_a++;
// ... Use this.
this._a++;
// ... Read instance field.
Console.WriteLine("B called: " + this._a);
}
}
class Program
{
static void Main()
{
// Create a new instance of the type Perl.
// ... The constructor calls method B.
// ... Then we call method B again.
Perl perl = new Perl();
perl.B();
}
}
Output
B called: 2
B called: 4
Tip: This approach can be useful in some contexts where you have a chain of method calls and constructors.
C# program that uses this as argument
using System;
class Net
{
public string Name { get; set; }
public Net(Perl perl)
{
// Use name from Perl instance.
this.Name = perl.Name;
}
}
class Perl
{
public string Name { get; set; }
public Perl(string name)
{
this.Name = name;
// Pass this instance as a parameter!
Net net = new Net(this);
// The Net instance now has the same name.
Console.WriteLine(net.Name);
}
}
class Program
{
static void Main()
{
Perl perl = new Perl("Sam");
}
}
Output
Sam
Terms: The term "precisely equivalent" means exactly equal. The term "disambiguate" means to make the difference clear.
Note: The standard refers to the "this" keyword as the instance expression. The keyword is an important part of the language.
Expressions: The standard goes to great detail about the nature of expressions in a 150-page chapter.