Advertisement



< Prev
Next >



C# this Keyword











In the next example, we will use this keyword to resolve the issue of shadowing.

//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

As you can see in our last example that within the UpdateA() method, we have used this keyword to access the instance variable, a, which has helped us to distinguish its name from the local variable a, and thereby resolving the issue of shadowing.



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