C# Keywords Tutorial Part 83: this
In C#, the this
keyword refers to the current instance of the class. It can be used to access instance members such as fields, properties, and methods. In this blog post, we will discuss how to use the this
keyword in C# with some code examples.
Using the this keyword to Access Instance Members
One of the most common uses of the this
keyword is to access instance members. Here’s an example:
public class Person { private string name; public Person(string name) { this.name = name; } public void SayHello() { Console.WriteLine("Hello, my name is " + this.name + "."); } }
In this example, the Person
class has a private field name
and a constructor that takes a name
parameter. The SayHello
method uses the this
keyword to access the name
field and print a greeting that includes the name.
Using the this Keyword to Avoid Naming Conflicts
Another use of the this
keyword is to avoid naming conflicts between class members and method parameters or local variables. Here’s an example:
public class Calculator { private int result; public Calculator(int result) { this.result = result; } public void Add(int result) { this.result += result; } public int GetResult() { return this.result; } }
In this example, the Calculator
class has a private field result
and a constructor that takes a result
parameter. The Add
method also takes a result
parameter, which is added to the result
field using the this
keyword to disambiguate between the two. The GetResult
method returns the value of the result
field.
Using the this Keyword in Extension Methods
Extension methods allow you to add functionality to existing classes without modifying their source code. You can use the this
keyword in an extension method to indicate that the method is an extension method. Here’s an example:
public static class StringExtensions { public static string Reverse(this string str) { char[] chars = str.ToCharArray(); Array.Reverse(chars); return new string(chars); } }
In this example, the StringExtensions
class has a static Reverse
method that takes a string
parameter and returns the reversed string. The method is marked with the this
keyword to indicate that it is an extension method for the string
class.
Leave a Reply