this Keyword in C#

WBOY
Release: 2024-09-03 15:29:08
Original
690 people have browsed it

In C#, ‘this’ keyword is used to refer to instance members of the current class from within an instance method or a constructor. It removes name ambiguity between method parameters and instance variables if they have the same name. Following are some uses of ‘this’ keyword in C#:

  • It can be used to invoke any method of the current object.
  • It can be used to invoke another constructor from the constructor of the same class.
  • It can be used as a parameter for a method call that takes the object of the same class as a parameter.

Syntax with Explanation:

The syntax of using ‘this’ keyword in C# is as follows:

this.instance_variable
Copy after login

In the above syntax ‘this’ is the keyword and instance_variable is the name of the instance variable of the class.

To pass the object of the same class as a parameter to a method, the syntax will be:

method_name(this);
Copy after login

In the above syntax, ‘this’ keyword refers to the object of the current class and method_name is the name of the method to be called.

How does this Keyword work in C#?

‘this’ keyword in C# is used as a ‘this’ pointer for a class. It is used to represent the current instance of a class. In C#, ‘this’ pointer works only for nonstatic members of the class because ‘this’ works on the current instance and nonstatic members can be accessed by the instance of the class. ‘this’ pointer does not work for static variables and member functions because we do not need any instance to access them and they exist at the class level.

In some cases, it is not necessary to use ‘this’ keyword explicitly. Like when we call the method of the current class, we use this.method_name() instead of this, we can directly call the method without using ‘this’ keyword and in that situation, ‘this’ keyword will be added automatically by the compiler.

Let us understand above point with the help of pictorial representation as shown below:

this Keyword in C#

Examples of this Keyword in C#

There are many ways of using ‘this’ keyword in C#:

Example #1

It is used to refer variables and member functions of the current instance.

Code:

using System;
namespace keywords
{
class ThisDemo
{
//instance variable
public string Message;
public string GetMessage()
{
return Message;
}
public void SetMessage(string Message)
{
//"this.Message" refers to instance variable (class member)
this.Message = Message;
}
}
public class program
{
public static void Main()
{
ThisDemo obj = new ThisDemo();
obj.SetMessage("Hello world!");
Console.WriteLine(obj.GetMessage());
}
}
}
Copy after login

Output:

this Keyword in C#

Example #2

We can use ‘this’ keyword to call the method in the same class.

Code:

using System;
namespace keywords
{
public class Employee
{
void displaySalary()
{
//calling displayDetails() method of same class
this.displayDetails();
Console.WriteLine("Salary: Rs.50000");
}
void displayDetails()
{
Console.WriteLine("Name: ABC");
Console.WriteLine("ID: 123ABC");
}
public static void Main(String []args)
{
Employee emp = new Employee();
emp.displaySalary();
}
}
}
Copy after login

Output:

this Keyword in C#

Example #3

We can use ‘this’ keyword to call a constructor in the same class.

Code:

using System;
namespace keywords
{
class Student
{
// calling another constructor of the same class
public Student() : this("ABC")
{
Console.WriteLine("Parameterless Constructer of Student class");
}
//parameterized constructor
public Student(string Name)
{
Console.WriteLine("Parameterized constructor of Student class");
}
public void display()
{
Console.WriteLine("display() method of Student class");
}
}
public class program
{
public static void Main()
{
Student stud = new Student();
stud.display();
}
}
}
Copy after login

Output:

this Keyword in C#

Example #4

If a method takes an object of the same class as parameter then ‘this’ keyword can be used as a parameter while calling that method.

In the same way, a method can return the object of the same class by using ‘this’ keyword.

Code:

using System;
namespace keywords
{
public class Student
{
double marks;
//method taking object of same class as parameter
void display(Student stud)
{
Console.WriteLine("Marks of student: "+stud.marks);
}
//method returning object of same class
Student addGradeMarks(double marks)
{
this.marks = marks + 5;
display(this);
return this;
}
public static void Main(String[] args)
{
Student stud = new Student();
stud = stud.addGradeMarks(85);
}
}
}
Copy after login

Output:

this Keyword in C#

Example #5

Apart from these uses, an important use of ‘this’ keyword is that we can use it to declare indexers.

Code:

using System;
namespace keywords
{
public class World
{
private string[] continents = new string[7];
//declaring an indexer
public string this[int index]
{
get
{
return continents[index];
}
set
{
continents[index] = value;
}
}
}
public class ThisDemo
{
public static void Main()
{
World world = new World();
world[0] = "Asia";
world[1] = "Africa";
world[2] = "North America";
world[3] = "South America";
world[4] = "Antarctica";
world[5] = "Europe";
world[6] = "Australia";
for (int i = 0; i < 7; i++)
{
Console.Write(world[i]);
Console.Write("\n");
}
}
}
}
Copy after login

Output:

this Keyword in C#

Example #6

‘this’ keyword can also be used to declare extension methods.

Code:

using System;
namespace keywords
{
//Class1 contains three methods; we will add two more methods in it
//without re-compiling it
class Class1
{
public void Method1()
{
Console.WriteLine("Method1");
}
public void Method2()
{
Console.WriteLine("Method2");
}
public void Method3()
{
Console.WriteLine("Method3");
}
}
// Class2 contains Method4 and Method5 methods
//which we want to add in Class1 class
static class Class2
{
public static void Method4(this Class1 class1)
{
Console.WriteLine("Method4");
}
public static void Method5(this Class1 class1, string str)
{
Console.WriteLine(str);
}
}
public class ThisDemo
{
public static void Main(string[] args)
{
Class1 class1 = new Class1();
class1.Method1();
class1.Method2();
class1.Method3();
class1.Method4();
class1.Method5("Method5");
}
}
}
Copy after login

Output:

this Keyword in C#

Conclusion

  • ‘this’ keyword is used to represent the current instance of a class.
  • If instance variables and method parameters have the same name then ‘this’ keyword can be used to differentiate between them.
  • ‘this’ can be used to declare indexers.
  • We cannot use ‘this’ in a static method.

The above is the detailed content of this Keyword in C#. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!