- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
‘this’ keyword in C#
The “this” keyword in C# is used to refer to the current instance of the class. It is also used to differentiate between the method parameters and class fields if they both have the same name.
Another usage of “this” keyword is to call another constructor from a constructor in the same class.
Here, for an example, we are showing a record of Students i.e: id, Name, Age, and Subject. To refer to the fields of the current class, we have used the “this” keyword in C# −
public Student(int id, String name, int age, String subject) { this.id = id; this.name = name; this.subject = subject; this.age = age; }
Example
Let us see the complete example to learn how to work with the “this” keyword in C# −
using System.IO; using System; class Student { public int id, age; public String name, subject; public Student(int id, String name, int age, String subject) { this.id = id; this.name = name; this.subject = subject; this.age = age; } public void showInfo() { Console.WriteLine(id + " " + name+" "+age+ " "+subject); } } class StudentDetails { public static void Main(string[] args) { Student std1 = new Student(001, "Jack", 23, "Maths"); Student std2 = new Student(002, "Harry", 27, "Science"); Student std3 = new Student(003, "Steve", 23, "Programming"); Student std4 = new Student(004, "David", 27, "English"); std1.showInfo(); std2.showInfo(); std3.showInfo(); std4.showInfo(); } }
Advertisements