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 <p><strong>Output:</strong></p> <p><img src="/static/imghwm/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/172534855950216.jpg?x-oss-process=image/resize,p_40" class="lazy" alt="this Keyword in C#" ></p> <h4 id="Example">Example #6</h4> <p>‘this’ keyword can also be used to declare extension methods.</p> <p><strong>Code:</strong></p> <pre class="brush:php;toolbar:false">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!

C# and .NET provide powerful features and an efficient development environment. 1) C# is a modern, object-oriented programming language that combines the power of C and the simplicity of Java. 2) The .NET framework is a platform for building and running applications, supporting multiple programming languages. 3) Classes and objects in C# are the core of object-oriented programming. Classes define data and behaviors, and objects are instances of classes. 4) The garbage collection mechanism of .NET automatically manages memory to simplify the work of developers. 5) C# and .NET provide powerful file operation functions, supporting synchronous and asynchronous programming. 6) Common errors can be solved through debugger, logging and exception handling. 7) Performance optimization and best practices include using StringBuild

.NETFramework is a cross-language, cross-platform development platform that provides a consistent programming model and a powerful runtime environment. 1) It consists of CLR and FCL, which manages memory and threads, and FCL provides pre-built functions. 2) Examples of usage include reading files and LINQ queries. 3) Common errors involve unhandled exceptions and memory leaks, and need to be resolved using debugging tools. 4) Performance optimization can be achieved through asynchronous programming and caching, and maintaining code readability and maintainability is the key.

Reasons for C#.NET to remain lasting attractive include its excellent performance, rich ecosystem, strong community support and cross-platform development capabilities. 1) Excellent performance and is suitable for enterprise-level application and game development; 2) The .NET framework provides a wide range of class libraries and tools to support a variety of development fields; 3) It has an active developer community and rich learning resources; 4) .NETCore realizes cross-platform development and expands application scenarios.

Design patterns in C#.NET include Singleton patterns and dependency injection. 1.Singleton mode ensures that there is only one instance of the class, which is suitable for scenarios where global access points are required, but attention should be paid to thread safety and abuse issues. 2. Dependency injection improves code flexibility and testability by injecting dependencies. It is often used for constructor injection, but it is necessary to avoid excessive use to increase complexity.

C#.NET is widely used in the modern world in the fields of game development, financial services, the Internet of Things and cloud computing. 1) In game development, use C# to program through the Unity engine. 2) In the field of financial services, C#.NET is used to develop high-performance trading systems and data analysis tools. 3) In terms of IoT and cloud computing, C#.NET provides support through Azure services to develop device control logic and data processing.

.NETFrameworkisWindows-centric,while.NETCore/5/6supportscross-platformdevelopment.1).NETFramework,since2002,isidealforWindowsapplicationsbutlimitedincross-platformcapabilities.2).NETCore,from2016,anditsevolutions(.NET5/6)offerbetterperformance,cross-

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.


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

Atom editor mac version download
The most popular open source editor

SublimeText3 English version
Recommended: Win version, supports code prompts!

Dreamweaver CS6
Visual web development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software
