C# this
Keyword
Syntax
The keyword this
is used to refer to the current instance of the class. The syntax for using this
is as follows:
this.memberVariable = value;
this.MethodName();
Example
class Person
{
private string name;
public Person(string name)
{
this.name = name;
}
public void PrintName()
{
Console.WriteLine("My name is {0}.", this.name);
}
}
Output
Person person = new Person("John");
person.PrintName(); // Output: My name is John.
Explanation
In a class, there are two types of variables: class-level variables (or fields), and method-level variables (or parameters). The this
keyword refers to the current instance of the class, and is used to differentiate between the class-level variables and the method-level variables.
In the example above, this.name
refers to the class-level variable name
, while name
in the constructor refers to the method-level variable name
. this
is commonly used in constructors to initialize class-level variables.
Use
The this
keyword is used to refer to the current instance of the class, and is typically used to access class-level variables or methods. It is also commonly used in constructors to initialize instance-specific variables.
Important Points
- The
this
keyword is used to refer to the current instance of the class. - It is typically used to access class-level variables or methods.
this
is commonly used in constructors to initialize instance-specific variables.- It is also used to differentiate between class-level and method-level variables.
Summary
The this
keyword in C# is a powerful tool for working with class instances and accessing class-level variables and methods. It is commonly used in constructors to initialize instance-specific variables, and is a key part of creating well-designed, object-oriented C# code.