SoFunction
Updated on 2025-03-07

The main role of this keyword in C#

In C#,thisKeywords have the following main functions:

Reference the current object:thisUsed to refer to an instance of the current class. Can be passedthisKeywords to access the member variables, methods and properties of the current object.

class MyClass
{
    private int myVar;
    public void SetVar(int var)
    {
         = var; // Use this keyword to refer to the member variable of the current object    }
}

Distinguish between fields and local variables: When member variables and local variables have the same name, you can usethisKeywords to distinguish.

class MyClass
{
    private int myVar;
    public void SetVar(int myVar)
    {
         = myVar; // Use this keyword to specify member variables    }
}

Call other constructors in constructor: can be usedthisKeywords to call other constructors in the same class.

class MyClass
{
    private int myVar;
    public MyClass(int var)
    {
         = var;
    }
    public MyClass() : this(0) // Call another constructor    {
    }
}

Pass the current object to other methods or constructors: can be usedthisThe keyword passes the current object as a parameter to other methods or constructors.

class MyClass
{
    public void Method()
    {
        (this); // Pass the current object to another method    }
}

Use this to add extension method

using System;
public static class StringExtensions
{
    public static int WordCount(this string str)
    {
        return (new char[] { ' ', '.', '?' }, ).Length;
    }
}
class Program
{
    static void Main()
    {
        string sentence = "Hello, world! This is a sentence.";
        int wordCount = ();
        ($"The sentence has {wordCount} words.");
    }
}

Overall,thisKeywords are mainly used in C# to refer to the current object, distinguish between fields and local variables, call other constructors, and pass the current object to other methods or constructors.

This is the end of this article about the role of C# this keyword. For more related C# this keyword content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!