C# this Keyword
In C#, this is a keyword used to refer current class instance. It is mainly used to distinguish instance variables of the class and formal parameters defined in a constructor call. this can also be used to return current class object from a method. It can also be passed in a method.
C# this keyword Example1:
using System; public class Student { int id,batch; string name,course; public Student(int id,int batch,string name,string course) { this.id=id; this.batch=batch; this.name=name; this.course=course; } public void display() { Console.WriteLine(id+" "+batch+" "+name+" "+course); } } public class ThisExample { public static void Main(string[] args) { Student s1=new Student(101,2017,"Ayush Sharma","B. Tech."); Student s2=new Student(102,2016,"Krishna Kumar","B. Tech."); s1.display(); s2.display(); } }C# this Keyword Example 2: calling current class method by this
using System; public class ThisExample2 { public void m() { Console.WriteLine("Hey You Are in M Method"); } public void n() { this.m();//m() Console.WriteLine("Hey you Are in N method"); } public static void Main(string[] args) { ThisExample2 t1=new ThisExample2(); t1.n(); } }Output
Hey You Are in M Method Hey you Are in N methodC# this Keyword Example 3: passing this in a method
using System; public class Employee { public int id,age; public string name; public float salary; public Employee(int id,int age,string name,float salary) { this.id=id; this.name=name; this.age=age; this.salary=salary; } public void display() { Display.display(this); Console.WriteLine("printing inside employee class...."); Console.WriteLine(id+" "+name+" "+salary+" "+age); } public static void Main(string[] args) { Employee emp=new Employee(101,24,"Ravi malik",25000); emp.display(); } } public class Display { public static void display(Employee emp) { Console.WriteLine("printing inside Display class…"); Console.WriteLine(emp.id+" "+emp.name+" "+emp.salary+" "+emp.age); } }Output
printing inside Display clas... 101 Ravi malik 25000 24 printing inside employee class.... 101 Ravi malik 25000 24C# this keyword Example: Returning this from the method
using System; public class Employee { public Employee returnObject() { return this; } public void show() { Console.WriteLine("Inside Show Method..."); } public static void Main(string[] args) { Employee emp1=new Employee(); emp1.show(); Employee emp2=emp1.returnObject(); emp2.show(); } }Output
Inside Show Method... Inside Show Method...