The this keyword refers to the current instance for which a method is called. Static member functions do not have a this pointer. The this keyword can be used to access members from within constructors, instance methods, and instance accessors.
The following are common uses of this:
public Employee(string name, string alias) { this.name = name; this.alias = alias; }
CalcTax(this);
public int this [int param] { get { return array[param]; } set { array[param] = value; } }
It is an error to refer to this in a static method, static property accessor, or variable initializer of a field declaration.
In this example, this is used to qualify the Employee
class members, name
and alias
, which are hidden by similar names. It is also used to pass an object to the method CalcTax
, which belongs to another class.
// this example using System; public class Employee { public string name; public string alias; public decimal salary = 3000.00m; // Constructor: public Employee(string name, string alias) { // Use this to qualify the fields, name and alias: this.name = name; this.alias = alias; } // Printing method: public void printEmployee() { Console.WriteLine("Name: {0}\nAlias: {1}", name, alias); // Passing the object to the CalcTax method by using this: Console.WriteLine("Taxes: {0}", decimal.Format(Tax.CalcTax(this), "C")); } } public class Tax { public static decimal CalcTax(Employee E) { return (0.08m*(E.salary)); } } public class MainClass { public static void Main() { // Create objects: Employee E1 = new Employee ("John M. Trainer", "jtrainer"); // Display results: E1.printEmployee(); } }
Name: John M. Trainer Alias: jtrainer Taxes: $240.00
For additional examples, see class and struct.