Knowee
Questions
Features
Study Tools

What is “this” keyword in C#? When to use it?

Question

What is “this” keyword in C#? When to use it?

🧐 Not the exact question you are looking for?Go ask a question

Solution

In C#, "this" keyword refers to the current instance of the class. It is used to distinguish the class members (variables, methods) from the parameters when they have the same names.

Here is how you can use it:

  1. To refer to the current instance of the class: If you have a method in a class that needs to refer to the object that the method was called on, you can use "this" keyword.
public class MyClass
{
    private int myVariable;

    public void SetVariable(int myVariable)
    {
        this.myVariable = myVariable;
    }
}

In the above example, "this.myVariable" refers to the class member and "myVariable" refers to the method parameter.

  1. To pass the current object as a parameter to other methods: Sometimes, you may need to pass the current object to another method. In such cases, you can use "this" keyword.
public class MyClass
{
    public void MyMethod()
    {
        OtherMethod(this);
    }

    public void OtherMethod(MyClass myClass)
    {
        // Do something with myClass
    }
}

In the above example, "this" in "OtherMethod(this)" refers to the current instance of MyClass.

  1. To declare indexers: "this" keyword is also used to declare indexers.
public class MyClass
{
    private int[] array = new int[100];

    public int this[int i]
    {
        get { return array[i]; }
        set { array[i] = value; }
    }
}

In the above example, "this" keyword is used to declare an indexer that allows instances of MyClass to be indexed just like arrays.

This problem has been solved

Similar Questions

What is “this” keyword in C#? When to use it?

What is the use of the 'this' pointer in C++?It is used to refer to the current object of the classIt is used to declare static variablesIt is used to create a new objectIt is used to access the base class members

In OOP, what is the purpose of the "this" keyword?Question 16Answera.To reference the current object within a methodb.To declare a variable with class scopec.To instantiate a new objectd.To define a constructor for the class

What is the keyword ``this'' used for in Java? A. To declare a new object B. To refer to the current class object C. To create a new instance of a class D. To declare a new method

When is the keyword ``this'' used within a constructor or a method? A. To declare a new object B. To refer to the superclass object C. To differentiate instance variables from local variables with the same name D. To create a new instance of a class

1/3

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.