views:

229

answers:

9

We all know that this refers to the actual instance of a class...but it seems to me that most people are not using it. So, should I be using it?

My thoughts about it are as follows: Since this refers to the actual instance of a class, it should be used to access any member of that class.

  public void(String newValue) {
        this.privateVariable = newValue;
  }

This should guarantee that the value is not assigned to an object with the same name within the scope (which could also end up as undefined behavior, anyway). But, what if an underscore is used to separate private from non-private fields:

  public voud(String newValue) {
        _privateVariable = newValue;
  }

this seems in that case a little redundant and unnecessary.

So, are there good reasons to use or not use this? Or am I just racking my brain about nothing?

+7  A: 

Personally I only use it when it's necessary, e.g.

public MyClass(string name)
{
    this.name = name;
}

I prefer that to renaming the parameter or field from the most natural name. I don't use this where it's otherwise unnecessary though. Having said that, there's absolutely no harm in doing so - and if you feel that it makes your code clearer, that's a very good reason to use it.

Jon Skeet
What about `private`? I personally remove it when not needed on members.
leppie
@leppie: I used to remove it, but I've since changed my mind, and generally try to be explicit. See http://csharpindepth.com/ViewNote.aspx?NoteID=54
Jon Skeet
For some reason I never write `this` (unless I have to), but always write `private`. I don't like seeing anything without an access modifier. Maybe I've picked it up from Java...
Kobi
@leppie: Ever considered posting that comment on this thread? http://stackoverflow.com/questions/234075/what-is-your-best-programmer-joke
Anax
@Jon Skeet: Thanks :) @Anax: Not sure what you mean.
leppie
@leppie "I remove my `private` when it is not needed on members". It can be misinterpreted :)
Anax
@Anax - you better not be giggling.
Kobi
A: 

It is subjective, but I prefer not to have it unless it provides unambiguity.

Using unnecessary this is like saying 'Create New Person'.

You choose :)

leppie
+1  A: 
Richard
+2  A: 

Personally I make sure that I never have name collisions between class members and locally declared variables. This means I never use this. However its all about readability really. If you think a "this" will make your code more intuitively understandable then use it, if not then don't.

Chris
+1  A: 

My two cents: Underscores are ugly!

=> fields are just camelCase

=> confusion with camelCase local variables is possible

=> always qualify with this

Daniel Brückner
+1 for underscores are ugly!
JLWarlow
+1  A: 

I used to use this all the time - probably a habit from pythons explicit self argument. I like to be reminded of when I use instance state.

Using Resharper from JetBrains made me brake that habit, since it would always flag this as redundant.

Daren Thomas
You can tell ReSharper not to flag redudant `this` qualifiers. You can even instruct ReSharper to always use `this` if performing a clean-up or inserting a code snippet.
Daniel Brückner
Sure. But I didn't really want to spend a lot of time configuring my installation and then lobbying everyone else on the team to do the same...
Daren Thomas
I configured it once and then saved the config file in a safe place for later reuse if I have to change my development machine or sharing with other team mebers.
Daniel Brückner
:) But how did you do the politics game on getting your team members to use *your* configuration file as opposed to *their* configuration file? I'm just saying, sometimes sticking to the defaults is easier.
Daren Thomas
+5  A: 

Nobody mentionned that you must use this if the requirement is to make a StyleCop compliant code and do not violate the readability rule SA1101. According to the documentation,

A violation of this rule occurs whenever the code contains a call to an instance member of the local class or a base class which is not prefixed with ‘this.’.

Also, in my opinion, using this keyword must be encouraged even for non-StyleCop-compliant source code, since specifying this increases readability and reduces the risk of mixing between local (method-scope) and class (object-scope) variables.

MainMa
... whereas I would say it *reduces* readability by introducing visual clutter in situations where there's no confusion anyway. I usually find it's really obvious which variables are related to an instance of the class and which are local. Keeping your methods short helps with this too, of course.
Jon Skeet
@Jon Skeet: see http://stackoverflow.com/questions/1562540/why-does-stylecop-recommend-prefixing-method-or-property-calls-with-this/1562544#1562544 for several reasons explaining why `this` *increases* readability.
MainMa
@MainMa: That's really just one reason, split into two: it allows you to quickly distinguish between static, instance and local variables. Fine. However, that post doesn't mention the *cost*, in terms of visual clutter, obscuring the logic involved. I can't remember the last time I was reading through a method and got confused between the different types of variables. If you find yourself getting confused by that, then sure, making it explicit makes sense. As I don't, I'd rather have code where the *logic* is more easily visible.
Jon Skeet
I find this greatly helps to distinguish between local methods and external methods. I have some third-party code which does not use this, unless necessary, and it makes the code much harder to understand.
Daniel Rose
@Daniel: What do you mean by "local methods" and "external methods"? Local *variables* I know about, but not local *methods*.
Jon Skeet
@Jon Local method: Part of the class; external: From another class. With large classes (ex. custom WPF controls), it gets difficult to tell what they are doing in the class itself.
Daniel Rose
@Daniel: What about inherited methods? They're from another class, but could still be called with "this.Foo()"? Again, I can't say I've ever found this to be a problem... if I'm calling a method on a different object, that's obvious by the reference. If I'm calling an inherited method, I don't particularly care...
Jon Skeet
Finally, I think "So, should I be using it?" question must be flagged as subjective and argumentative, since most of the answers (including mine) are subjective and can only be subjective. Using `this` is about *style*. There is StyleCop, and its default rules are Microsoft *standard*. Anything other is just *a point of view*.
MainMa
@MainMa: I think it's definitely subjective - but I don't think it needs to be argumentative. I think there's value to discussing these things.
Jon Skeet
@Jon Skeet: I agree with you. Especially with the last sentence.
MainMa
+2  A: 

I like using this. as it brings up intellisene which means I can quite often type a few letters of the method, variable and auto complete - makes writing code faster!

JLWarlow
Invoking intellisense is shorter than typing `this.`.
leppie
there is usually a keyboard shortcut to activate intellisense. In my VS its ctrl-space that does the job (can't remember if that is standard or something I chose). So its actually more work to type "this." to get intellisense working than to just hit the keyboard shortcut. :) Hopefully I've just raised your productivity by 0.000001% or something. ;-)
Chris
Actually, `this.` filters intellisense, and display only members - very useful when you derive a class. Ctrl+Space shows a lot more options - static methods, **all types in your context**. This is just a *tool* though, and has no effect on the produced code.
Kobi
@leppie true, but as Kobi says it displays only members which I find more usefull.@Kobi - indeed; using intellisense makes writing code faster but not better - better is still down to the jelly between the ears :-)
JLWarlow
+3  A: 

You should use the naming-convention approach. (The one with the undescore.)

There are dangers when changing code with the "this" approach if "this" is forgotten.

Why? If MyMethod in the followin class is later changed to include a local variable called "something" the compiler still compiles, while the code no longer does whats expected.

class MyClass
{
    int something = 10;

    void MyMethod()
    {
        //...lots'a code here...

        something = 20;  //Which var is something pointing at?
    }
}

Changing it to the following will introduce a bug...

class MyClass
{
    int something = 10;

    void MyMethod()
    {
        int something = 0;
        //...lots'a code here...

        something = 20;  //Which var is something pointing at?
    }
}

So unless ALL developers working on your team, sharing code, always will remember "this"; don't go that way!

Arjan Einbu
The danger is the "lots'a code here" bit, to me. When a method ends up being large, all kinds of bugs can creep in.
Jon Skeet
Ok, change "lots'a" for "some" ;-) Still thats all it takes to get it wrong...
Arjan Einbu