this Keyword in C#
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
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);
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:
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()); } } }
Output:
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(); } } }
Output:
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(); } } }
Output:
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); } } }
Output:
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"); } } } }
Output:
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"); } } }
Output:
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Guide to Active Directory with C#. Here we discuss the introduction and how Active Directory works in C# along with the syntax and example.

Guide to Random Number Generator in C#. Here we discuss how Random Number Generator work, concept of pseudo-random and secure numbers.

Guide to C# Data Grid View. Here we discuss the examples of how a data grid view can be loaded and exported from the SQL database or an excel file.

Guide to Factorial in C#. Here we discuss the introduction to factorial in c# along with different examples and code implementation.

The difference between multithreading and asynchronous is that multithreading executes multiple threads at the same time, while asynchronously performs operations without blocking the current thread. Multithreading is used for compute-intensive tasks, while asynchronously is used for user interaction. The advantage of multi-threading is to improve computing performance, while the advantage of asynchronous is to not block UI threads. Choosing multithreading or asynchronous depends on the nature of the task: Computation-intensive tasks use multithreading, tasks that interact with external resources and need to keep UI responsiveness use asynchronous.

Guide to Patterns in C#. Here we discuss the introduction and top 3 types of Patterns in C# along with its examples and code implementation.

Guide to Prime Numbers in C#. Here we discuss the introduction and examples of prime numbers in c# along with code implementation.

The history and evolution of C# and C are unique, and the future prospects are also different. 1.C was invented by BjarneStroustrup in 1983 to introduce object-oriented programming into the C language. Its evolution process includes multiple standardizations, such as C 11 introducing auto keywords and lambda expressions, C 20 introducing concepts and coroutines, and will focus on performance and system-level programming in the future. 2.C# was released by Microsoft in 2000. Combining the advantages of C and Java, its evolution focuses on simplicity and productivity. For example, C#2.0 introduced generics and C#5.0 introduced asynchronous programming, which will focus on developers' productivity and cloud computing in the future.
