Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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;
    }
}

While I presume the answer will likley be user preference, is it best practice to use the this keyword within a class for local values?

like image 305
ghost Avatar asked Mar 15 '09 06:03

ghost


3 Answers

In the spirit of DRY, I would say this is not a particularly useful practice in general. Almost any use of this can be shortened to an equivalent expression by just removing the this.

One exception is if you have a local parameter which happens to have the same name as another class member; in that case you must distinguish between the two with this. But this is a situation you can easily avoid, by simply renaming the parameter.

like image 102
John Feminella Avatar answered Oct 05 '22 23:10

John Feminella


I use the this keyword almost only when some member is hiding another, and when I need to pass the current class instance to a method for example:

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;
    } 


}
like image 23
Christian C. Salvadó Avatar answered Oct 05 '22 23:10

Christian C. Salvadó


I would say it depends on personal preference for your own coding and on the team/company coding standards for your code at work. Personally, I try to keep both personal and "professional" coding standards the same--it reduces confusion, etc.

I prefer to use "this" on all class-level functions and variables. By using "this" you can immediately tell if the item is a class member or not. Also,I prefer to use "base" on members belonging to any base classes. It's not necessary, but it helps readability, esp if someone unfamiliar with your code is reading it.

like image 35
Muad'Dib Avatar answered Oct 05 '22 23:10

Muad'Dib