views:

243

answers:

4

Hi all,

I'm working through the book Head First C# (and it's going well so far), but I'm having a lot of trouble wrapping my head around the syntax involved with using the "this." keyword.

Conceptually, I get that I'm supposed to use it to avoid having a parameter mask a field of the same name, but I'm having trouble actually tracking it through their examples (also, they don't seem to have a section dedicated to that particular keyword, they just explain it and start using it in their examples).

Does anyone have any good rules of thumb they follow when applying "this."? Or any tutorials online that explain it in a different way that Head First C#?

Thanks!

+1  A: 

I write this. if and only if it enhances readability, for example, when implementing a Comparable interface (Java, but the idea is the same):

public void compareTo(MyClass other) {
  if (this.someField > other.someField) return 1;
  if (this.someField < other.someField) return -1;
  return 0;
}

As to parameter shadowing (e.g. in constructors): I usually give those a shorter name of the corresponding field, such as:

class Rect {
  private int width, height;
  public Rect(int w, int h) {
    width = w;
    height = h;
  }
}
Thomas
+9  A: 

Personally I only use it when I have to which is:

  • Constructor chaining:

    public Foo(int x) : this(x, null)
    {
    }
    
    
    public Foo(int x, string name)
    {
        ...
    }
    
  • Copying from a parameter name into a field (not as common in C# as in Java, as you'd usually use a property - but common in constructors)

    public void SetName(string name)
    {
        // Just "name = name" would be no-op; within this method,
        // "name" refers to the parameter, not the field
        this.name = name;
    }
    
  • Referring to this object without any members involved:

    Console.WriteLine(this);
    
  • Declaring an extension method:

    public static TimeSpan Days(this int days)
    {
        return TimeSpan.FromDays(days);
    }
    

Some other people always use it (e.g. for other method calls) - personally I find that clutters things up a bit.

Jon Skeet
The keyword is also used for extension methods.
masfenix
@Jon, I'm interested in your thoughts on your second example. Personally, I would just name the backing field something different to avoid the clashing, and remove the need for the 'this' keyword. (Usually something like '_name' for private member fields)
Simon P Stevens
@masfenix: Thanks, will add that. @Simon: No, I like this. I don't like prefixes (I find that interferes with my reading), and if I've chosen a name for a concept then presumably it's the best one I can think of. The pain of writing "this." occasionally is relatively small.
Jon Skeet
@Jon. So essentially, it's a personal thing, no technical reason to prefer one over the other. Thanks.
Simon P Stevens
A: 

Basically, this gives you a reference to the current object. You can use it to access members on the object, or to pass the current object as parameters into other methods.

It is entirely unnecessary in almost all cases to place it before accessing member variables or method calls, although some style guidelines recommend it for various reasons.

Personally, I make sure I name my member variables to be clearly different from my parameters to avoid ever having to use 'this.'. For example:

private String _someData;
public String SomeData
{
    get{return _someData;}
    set{_someData = value;}
}

It's very much an individual preference though, and some people will recommend that you name the property and member variable the same (just case difference - 'someData' and 'SomeData') and use the this keyword when accessing the private member to indicate the difference.

So as for a rule of thumb - Avoid using it. If you find yourself using it to distinguish between local/parameters variables and member variables then rename one of them so you don't have to use 'this'.

The cases where I would use it are multiple constructors, passing a reference to other methods and in extension methods. (See Jon's answer for examples)

Simon P Stevens
+2  A: 

StyleCop's default coding style enforces the following rule:

A1101: The call to {method or property name} must begin with the 'this.' prefix to indicate that the item is a member of the class.

Which means that every method, field, property that belongs to the current class will be prefixed by this. I was initially resistant to this rule, which makes your code more verbose, but it has grown on me since, as it makes the code pretty clear. This thread discusses the question.

Mathias
I think that's among the dumbest StyleCop rules, second only to placing a comment on every private field.
John Saunders