The this keyword helps you refer to the current object inside its own class. It makes your code clear and avoids confusion when names overlap.
0
0
This keyword behavior in C Sharp (C#)
Introduction
When you want to access the current object's fields or methods inside a class.
When constructor parameters have the same names as class fields and you want to distinguish them.
When you want to pass the current object as a parameter to another method.
When you want to call one constructor from another constructor in the same class.
Syntax
C Sharp (C#)
this.memberNamethis always refers to the current instance of the class.
You can use this to call fields, properties, methods, or constructors.
Examples
Using
this to distinguish between the field and the parameter with the same name.C Sharp (C#)
class Person { private string name; public Person(string name) { this.name = name; // 'this.name' is the field, 'name' is the parameter } public void ShowName() { Console.WriteLine(this.name); // Access current object's field } }
Using
this to call one constructor from another in the same class.C Sharp (C#)
class Counter { private int count; public Counter() : this(0) { } // Calls another constructor public Counter(int start) { this.count = start; } }
this can be used to refer to the current object itself.C Sharp (C#)
class Example { public void PrintSelf() { Console.WriteLine(this); // Prints the current object reference } }
Sample Program
This program creates a Person object with the name "Alice". It uses this to set and access the name field and to print the current object reference.
C Sharp (C#)
using System; class Person { private string name; public Person(string name) { this.name = name; // Use 'this' to refer to the field } public void Greet() { Console.WriteLine($"Hello, my name is {this.name}."); } public void ShowThis() { Console.WriteLine(this); // Shows the object reference } } class Program { static void Main() { Person p = new Person("Alice"); p.Greet(); p.ShowThis(); } }
OutputSuccess
Important Notes
When you print this directly, it shows the class name unless you override ToString().
You don't always need to use this if there is no naming conflict, but it can improve clarity.
Summary
this refers to the current object inside its class.
Use this to avoid confusion when names overlap.
this can call other constructors or pass the current object.