this Reference

The this keyword refers to the current instance of a class and it is also used as a modifier of the first parameter of an extension method.

public class Panda
{
   public Panda Mate;
   public void Marry (Panda partner)
  {
     Mate = partner;
     partner.Mate = this;
  }
}

The this reference is valid only within non static members of a class or struct.

this is used to qualify members hidden by similar names.

public Employee(string name, string alias)
{
  //this to qualify the fields, name and alias
  this.name = name;
  this.alias = alias;
}

this is used to pass an object as a parameter to other methods

CalTax(this);

this is to declare indexers.

public int this[int param]
{
    get { return array[param]; }
    set { array[param] = value; }
}

Example

namespace Rextester
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Employee E1 = new Employee("Just","Lee");
            E1.printEmployee();
        }
    }
    
    class Employee
    {
       //fields
       private string name;
       private string alias;
       private decimal salary = 3000.00m;
        
       //constructor
       public Employee(string name, string alias)
       {
           this.name = name;
           this.alias = alias;
       }
        
       //print 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:C}", Tax.CalcTax(this));
       }
        
        //property
        public decimal Salary
        {
            get { return salary;}
        }
    }
    
    class Tax
    {
       public static decimal CalcTax(Employee E)
       {
         return 0.08m * E.Salary;
       }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *