Use of the "this" keyword

August 29th, 2008

Pubb just posted this tweet “in your c# code: this. or no this.? why?” and my reply was too long for Twitter so I’ll post it here.

The “this” keyword refers to the current instance of the class. When a variables in the local scope have different names than the instance fields the “this” keyword can be used to differentiate an instance field from a variable (or input parameter) in the local scope. If an input parameter has the same name as the instance field then you are required to use the “this” keyword to access the instance field.

Some developers prefer to use a prefix on instance fields such as an underscore “” or “m” to differentiate them from other variables. In this case I think the use of “this” is redundant and should be omitted.

I prefer to follow the .NET Design Guidelines Field Usage Guidelines which states “Do not apply a prefix to field names or static field names” so I don’t have “” or “m” prefixes on my instance fields. If I am accessing a field from other members I try to keep those members short enough so that you can clearly see the definitions of all variables/parameters without scrolling which makes it very easy to determine what is a local variable or input parameter and what is an instance field. In this case I only wind up using “this” in my constructors if the input parameters to the constructor have the same name as the instance field.

1 Response to “Use of the "this" keyword”

  1. Jake Good Says:
    I agree with you completely... I even apply those rules when I'm writing Ruby code (self.instance_variable)... but a lot of stylistic Ruby guys don't... :: shrugs ::

Sorry, comments are closed for this article.