this keyword is used to refer to the current instance of the class. It is used to access members from the constructors, instance methods, and instance accessors. this keyword is also used to track the instance which is invoked to perform some calculation or further processing related to that instance. Following are the different ways to use ‘this’ keyword in C# :
Program 1: Using ‘this’ keyword to refer current class instance members
csharp
using System;
namespace geeksforgeeks {
class Geeks {
public string Name;
public string GetName()
{
return Name;
}
public void SetName( string Name)
{
this .Name = Name;
}
}
class program {
public static void Main()
{
Geeks obj = new Geeks();
obj.SetName( "Geeksforgeeks" );
Console.WriteLine(obj.GetName());
}
}
}
|
Program 2 : Using this() to invoke the constructor in same class
csharp
using System;
namespace geeksforgeeks {
class Geeks {
public Geeks() : this ( "geeks" )
{
Console.WriteLine( "Non-Parameter Constructor Called" );
}
public Geeks( string Name)
{
Console.WriteLine( "Parameter Constructor Called" );
}
}
class program {
public static void Main()
{
Geeks obj = new Geeks();
}
}
}
|
Output:
Parameter Constructor Called
Non-Parameter Constructor Called
Program 3: Using ‘this’ keyword to invoke current class method
csharp
using System;
class Test {
void display()
{
this .show();
Console.WriteLine( "Inside display function" );
}
void show()
{
Console.WriteLine( "Inside show function" );
}
public static void Main(String []args)
{
Test t1 = new Test();
t1.display();
}
}
|
Output
Inside show function
Inside display function
Program 4: Using ‘this’ keyword as method parameter
csharp
using System;
class Test
{
int a;
int b;
Test()
{
a = 10;
b = 20;
}
void display(Test obj)
{
Console.WriteLine( "a = " + a + " b = " + b);
}
void get ()
{
display( this );
}
public static void Main(String[] args)
{
Test obj = new Test();
obj. get ();
}
}
|
Program 5: Using this keyword to declare an indexer
csharp
using System;
namespace geeksforgeeks {
class Geeks {
private string [] days = new string [7];
public string this [ int index]
{
get
{
return days[index];
}
set
{
days[index] = value;
}
}
}
class Program {
public static void Main()
{
Geeks g = new Geeks();
g[0] = "Sun" ;
g[1] = "Mon" ;
g[2] = "Tue" ;
g[3] = "Wed" ;
g[4] = "Thu" ;
g[5] = "Fri" ;
g[6] = "Sat" ;
for ( int i = 0; i < 7; i++)
Console.Write(g[i] + " " );
}
}
}
|
Output:
Sun Mon Tue Wed Thu Fri Sat
Last Updated :
15 Nov, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...