what is difference between use "this" and omit it?

兰树豪 381 Reputation points
2022-10-25T07:26:05.707+00:00

what is difference between use "this" and omit it?

 class MyClass  
    {  
        private int myVar;  
  
        public int MyProperty  
        {  
            get { return this.myVar; }  
            set { this.myVar = value; }  
        }  
    }  

class MyClass  
    {  
        private int myVar;  
  
        public int MyProperty  
        {  
            get { return myVar; }  
            set { myVar = value; }  
        }   
  
    }  

seems no different

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,784 questions
Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
5,193 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,011 questions
0 comments No comments
{count} votes

Accepted answer
  1. Sreeju Nair 12,366 Reputation points
    2022-10-25T07:53:31.51+00:00

    The "this" keyword refers to the current instance of the class. In the example you provided, whether you use this or not, it have the same meaning.

    Consider the following example

    class MyClass
    {
    private int myVar;
    public MyClass(int myVar)
    {
    this.myVar=myVar;
    }
    }
    In the above example, you have a constructor that uses the same variable name "myVar". so inside the constructor, simply refering "myVar" means the argument, and this.myVar refer to the class variable.

    Hope this helps.

    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.