this keyword in C# with programming uses and examples. – In C# programs, this keyword is used for following.
- To refer current class fields(instance variables).
- To invoke the current class method.
- To invoke the current class constructor(implicitly).
- To pass as a current class object as a parameter in the methods.
- To pass a current class object in the constructor.
- To return the current class instance from the method
Using this keyword to refer class fields
This keyword is used to refer class fields to avoid ambiguity between parameters of constructor or functions and class fields. For example; in below class constructor, if we don’t use this keyword then we don’t know if parameter is initialized to class field or class field is initialized to parameter.
public class Car {
string model;
double price;
public Car(String model, double price) {
model =model;
price=price;
}
}
If we use this keyword then it is clear indication that we are initializing class fields by constructor parameters.
public class Car {
String model;
double price;
public Car(String model, double price) {
this.model=model;
this.price=price;
}
}
Hiding variable Example:
If we have a local variable in a method having same name as field, then compiler will prefer local variable and hide the class field variable. If we want to use class field variable in the method then we must use this keyword before class field variable to access that.
class Car {
String model;
double price;
public Car(String model, double price) {
this.model = model;
this.price = price;
}
public void displayPrice() {
double price = 2000;// dummy price
Console.WriteLine("dummy price " + price);
Console.WriteLine("Actual price " + this.price);
}
}
public class Sample
{
public static void Main(String[] args)
{
Car m = new Car("Maruti", 100000);
Car h = new Car("Honda", 300000);
m.displayPrice();
}
}
Output:
dummy price 2000.0
Actual price 100000.0
If we don’t use this keyword before class field variable in the method displayPrice then the dummy price and actual price values will be same that is 2000.0
Using this keyword to refer class method
This keyword can also be used in class method to improve readability. For example In below program we have used this keyword in highestPrice method to make the current object and incoming object in the parameter readable.
class Car
{
String model;
double price;
public Car(String model, double price)
{
this.model = model;
this.price = price;
}
double getPrice()
{
return this.price;
}
String getModel()
{
return this.model;
}
public void highestPriceCar(Car c) {
if (this.getPrice() > c.getPrice()) {
Console.WriteLine(this.getModel() + " is the car with highest price");
} else {
Console.WriteLine(c.getModel() + " is the car with highest price");
}
}
}
public class Sample
{
public static void Main(String[] args)
{
Car m = new Car("Maruti", 100000);
Car h = new Car("Honda", 300000);
m.highestPriceCar(h);
}
}
Output:
Honda is the car with highest price
C# program to invoke current class constructor(implicitly).
//Write a C# program to invoke cutternt class constructor(implicitly).
class AddCalculator {
// declared instance variable a,b,c as a interger.
int a;
int b;
int c;
public AddCalculator(int a, int b, int c) :this(a, b){
/*
* // "this" syntex always will be first
//statement of Constructor.It called
* two parameterized constructor. This called implicitly),
//if I dont call
* it,then it called implicitly as this() method
*/
// refer to current classs's instance variable
//and initialized method.
this.a = a;
this.b = b;
this.c = c;
// This is final statement to display.
Console.WriteLine("Add of three number is= " + (a + b + c));
}
public AddCalculator(int a, int b):this(a) {
/*
* // "this" syntex always will be
//first statement of Constructor. It called
* one parameterized constructor.)
*/
// refer to current classs's instance variable
//and initialized method.
this.a = a;
this.b = b;
// This statement will be displayed third.
Console.WriteLine("Add of three number is= " + (a + b));
}
public AddCalculator(int a): this()
{
/*
* // "this" syntex always will be first statement
//of Constructor. It called
* default constructor.)
*/
// This statement will be displayed second.
Console.WriteLine("Add of three number is= " + (a));
}
public AddCalculator() {
// After, call is completed. This
// statement will be displayed first.
Console.WriteLine("Calculation completed");
}
}
public class ConstructorExample {
public static void Main(String[] args) {
// Firstly, three parameterized constructor
// is executed when object of AddCalculator class is created
AddCalculator add = new AddCalculator(10, 10, 10);
}
}
Output
Calculation completed
Add of three number is= 10
Add of three number is= 20
Add of three number is= 30
C# program to pass object or an argument through methods using this keyword.
//Write a C# program to pass object or an argument
//through methods using this keyword.
//Here,two reference are referring the same object
class Abc {
Bcc obj;
// Passed object throughr the metod.
public void m(Bcc obj) {
// initialized
this.obj = obj;
}
// Defined display() method that assign
//data by Bcc class object.
public void display() {
Console.WriteLine("data= " + obj.data);
}
}
public class Bcc {
public int data = 30;
public void p() {
// Here, Object of Abc class is created.
Abc ab = new Abc();
/// pass the current object througth method m()
// that is Bcc class's object.
ab.m(this);
// called display() method.
ab.display();
}
}
public class PassMethodThis {
public static void Main(String[] args) {
// Constructor Of class Bcc is executed when object creation.
// But here is not any constructor.
Bcc aa = new Bcc();
// called the p() method of class A.
aa.p();
}
}
Output
data= 30
C# program to pass object or an argument through constructor using this keyword.
//Write a C# program to pass object or an
//argument through constructor using this keyword.
//Here,two reference are referring the same object.
public class Aaaa {
B obj;
// Passed object throughr the metod.
public Aaaa(B obj) {
// initialized
this.obj = obj;
}
// Defined display() method that assign data by B class object.
public void display() {
Console.WriteLine ("data " + obj.data);
}
}
public class B {
public int data = 10;
public B() {
// Here, Object of Aaaa class is created and constructor
//of class Aaaa is executed..
Aaaa aaaa = new Aaaa(this);
// called display() method.
aaaa.display();
}
}
public class PassArgumentConstructor {
public static void Main(String[] args) {
// Constructor Of class B is executed when object creation.
B b = new B();
}
}
Output
data 10
C# program to return the current class object.
class Student{
//Both are instance variable
public String name;
public int age;
//
public Student(String name, int age)//these are local
//variable which are in parameter.
{
//this keyword referred to current class instance variables.
this.name=name;
this.age=age;
}
public Student getStudent() {
//here this keyword returns current class object.
//which is instance of current class.
// that returns " Packagename.className+@+hashcode of object. "
return this;//here return Object of student;
}
}
public class ReturnThisExample {
public static void Main(String[] args) {
Student studentObject=new Student("sovan",23);
//By default called toString() method that returns
// " Packagename.className+@+hashcode of object. "
Console.WriteLine("studentObject: "+studentObject);
//By default called toString() method that returns
// " Packagename.className+@+hashcode of object. "
Console.WriteLine("studentObject: "+studentObject.getStudent());
//Called name variable at this object location
Console.WriteLine("name: "+studentObject.getStudent().name);
//Called name variable at this object location
Console.WriteLine("age: " + studentObject.getStudent().age);
}
}
output:
studentObject: this_keyword_with_Current_class_object.Student
studentObject: this_keyword_with_Current_class_object.Student
name: sovan
age: 23