this keyword in c# code example

Example 1: this keyword in c#

class Employee
{
    private string name;
    private string alias;
    private 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:C}", Tax.CalcTax(this));
    }

    public decimal Salary
    {
        get { return salary; }
    }
}

class Tax
{
    public static decimal CalcTax(Employee E)
    {
        return 0.08m * E.Salary;
    }
}

class MainClass
{
    static void Main()
    {
        // Create objects:
        Employee E1 = new Employee("Mingda Pan", "mpan");

        // Display results:
        E1.printEmployee();
    }
}
/*
Output:
    Name: Mingda Pan
    Alias: mpan
    Taxes: $240.00
 */

Example 2: use of this in programming in c#

using System.IO;
using System;

class Student {
   public int id, age;  
   public String name, subject;

   public Student(int id, String name, int age, String subject) {
      this.id = id;
      this.name = name;
      this.subject = subject;
      this.age = age;
   }

   public void showInfo() {
      Console.WriteLine(id + " " + name+" "+age+ " "+subject);
   }
}

class StudentDetails {
   public static void Main(string[] args) {
      Student std1 = new Student(001, "Jack", 23, "Maths");
      Student std2 = new Student(002, "Harry", 27, "Science");
      Student std3 = new Student(003, "Steve", 23, "Programming");
      Student std4 = new Student(004, "David", 27, "English");

      std1.showInfo();
      std2.showInfo();
      std3.showInfo();
      std4.showInfo();
   }
}