views:

261

answers:

6

I like to use 'this' statement for all non-local variables: for properties, for class variables, etc. I do this for code easy reading, easy understanding where from this variable has got.

object someVar;

object SomeProperty { get; set }

void SomeMethod(object arg1, object arg2)
{
  this.SomeProperty = arg1;
  this.someVar = arg2;
}

How do you think, what is proper way to use 'this'?

+2  A: 

I only used to use it in constructors so that I can have the member variables the same name as the ctor parameters for consistency. Now that I'm using auto properties, I don't use it anywhere at all, unless I have member variables that I don't want as properties (I just don't like having totally private properties; seems weird somehow).

Neil Barnwell
+6  A: 

this is a good thing. this disambiguates.

Ô_o:

public class Foo
{
    private string bar

    public Foo(string bar)
    {
     bar = bar;
    }
}

Underscores are lame (it's C#, not C++):

public class Foo
{
    private string _bar

    public Foo(string bar)
    {
     _bar = bar;
    }
}

Yay:

public class Foo
{
    private string bar

    public Foo(string bar)
    {
     this.bar = bar;
    }
}
Chris
+1  A: 

Typically I would use the 'this' keyword to remove any ambiguity between class/object variables and method parameters.

Andy Rose
+1  A: 

Using this has two compulsory roles

  • when you have to break an ambiguity between a function parameter, a local variable name and a propertie. If I were to use this, it would be in constructors only, because it's the only place it makes sense to use the same name.

    void SomeMethod(object SomeProperty, object someVar) { this.SomeProperty = SomeProperty; this.someVar = someVar; }

  • whenever you need to pass a reference to the current object to another method. Having to pass your object too often is a code smell.

Anything else would probably be too verbose. Don't use what you don't need.

Johan Buret
A: 

I only use it when when constructor or method parameters collide with member variables of some sort. Could be properties or fields or whatever. This doesn't really happen too often though. So I seldom use it.

I think ReSharper removes this. where it is not needed. Perhaps by default... it does here, but not sure if it was the default behaviour or not :p

Svish
+1  A: 

I like to use it when assigning to inherited properties.

Tomas