Advertisement



< Prev
Next >



C# this Keyword











Using this keyword, we can access the currently executing object and its instance variables.

//C# Example of this keyword used to resolvd the shadowing issue

using System;

class A
{
//Instance variable
int a = 20;		    

//Defining the method SetA()
//Which should update the value of the instance variable, a.
//But its local variable has the same name, a,
//As instance variable of the class A, so it won't happen
public void UpdateA(int a) 
{
	//Accessing an instance variable with this keyword, 
	//to differ it from a local variable with the same name
	this.a = a; 
}

//Defining the Main() method
public static void Main(String[] ar)
{
	//Creating an object of class A
	A ob = new A();
	
	//Accessing the value of instance variable, a, before calling the UpdateA() method
	Console.WriteLine("Before calling UpdateA(), the value in instance variable, a: "+ ob.a);

	//Calling the UpdateA() method and passing it 100
	//to set the value of the instance variable, a
	ob.UpdateA(100);   

	//Accessing the value of instance variable, a, after calling the UpdateA() method
	Console.WriteLine("After calling UpdateA(), the value in instance variable, a: "+ ob.a);
}
}


Output-


Before calling UpdateA(), the value in instance variable, a: 20
After calling UpdateA(), the value in instance variable, a: 100

In the UpdateA() method, we have accessed an instance variable a, with this keyword, in order to distinguish its name from a local variable a, which resolves the shadowing issue.



Please share this article -





< Prev
Next >
< C# Method Return Types
C# Static Keyword >



Advertisement

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement



Notifications



Please check our latest addition

C#, PYTHON and DJANGO


Advertisement