The this
keyword in C# is a pointer reference to the current instance or object of a struct or class.
this
is the preferred way to refer to members or parameters of classes or structs whose names may not be unique in a given context, and may only be used with non-static class or struct methods.
this
with member variables or functionsYou can use the this
keyword to access member variables or functions within a class. This is also useful when the parameter names are the same as the member variables, as this
helps to distinguish between them.
When you access members within constructors, you must put the this
keyword before the function or member that you are accessing.
Below is an example of how to use the this
keyword with a member variable.
using System;class Person {private string name = "";private int age = 0;public Person(string name, int age) {this.name = name;this.age = age;}public void print() {Console.WriteLine("Name: " + getName());Console.WriteLine("Age: " + getAge());}public string getName() { return name; }public int getAge() { return age; }}class HelloWorld{static void Main(){Person person = new Person("John", 30);person.print();}}
In the example above, you can see that we use the this
keyword within the constructor and the print()
method to resolve ambiguity between the parameters and member variables of the same name.
this
can also be used to pass the current object to another method.