If you always refer to local class variables with "this"

In C #, you can refer to values ​​in a class using the 'this' keyword.

class MyClass
{
    private string foo;

    public string MyMethod()
    {
        return this.foo;
    }
}

Although I believe the answer would be preferable for the user, is it better to use this keyword inside the class for local values?

+5
source share
8 answers

In the spirit of DRY , I would say that this is not a particularly useful practice in general. Almost any use thiscan be reduced to an equivalent expression by simply deleting it this.

- , , ; this. , , .

+12

this , - , , :

class Employee
{
    private string name;
    private string address;

    // Pass the current object instance to another class:
    public decimal Salary 
    {
        get { return SalaryInfo.CalculateSalary(this); }
    }


    public Employee(string name, string address) 
    {
        // Inside this constructor, the name and address private fields
        // are hidden by the paramters...
        this.name = name;
        this.address = address;
    } 


}
+4

, / . , "" - ..

"this" . "this", , . , "" , . , , esp, - .

+3

. , , , var .

: , , , , . . , : , (, , ) , , vars, (imho!), 'this' - .

+1

. , , . , , , , , .

"_" -, . , , . .

"" , ReSharper, " " .

+1

- . , , this , , . (- , Microsoft FxCop .NET?)

, this , , . , :

  • ( this)
  • ( )
  • ( )

, 5 this.. , , dispose() , , -, . , , this. intellisense .

+1

JavaScript, ! , , . , "" -, , IDE , .

VS 2010 , , WPF, this. -, . , , , , , this., .

+1

, , .

The reason for this is that if you later add a local variable with the same name, you will need to rename all the class variables with this., so why not save your future yourself and miss out?

0
source

All Articles