1

I would like to know if I get it correctly: also with this keyword I can distinct between fields and variables? Like this:

class X
{
  int x;
  public X(int x)
  {
    this.x=x;
  } 
}
Loj
  • 1,159
  • 3
  • 14
  • 23
  • Hm, I might be a bit old fashioned in this point, but I always require the usage of the `m` prefix for fields of a class or struct. – Paul Michalik Jan 08 '11 at 12:47

1 Answers1

9

Yes, if a method parameter (or local variable) has the same name as a field, you need to use this to distinguish the two. Also, StyleCop is very vocal about every class member access being done through this, but whether that's a good idea or not may be up to debate. It makes things more clear, but also adds much visual clutter.

Joey
  • 344,408
  • 85
  • 689
  • 683
  • 2
    This is known as "shadowing" and it's not just StyleCop that is vocal about this =D (http://leepoint.net/notes-java/data/variables/60shadow-variables.html) –  Jan 08 '11 at 12:29
  • @Hypnos: StyleCop complains about *every* use of a class member without `this` or `base`. Not just those where a local variable would shadow it. Agreed though, that it usually is poor practice to have a local variable shadow a class member, although for backing fields for properties and constructor arguments I guess it's mostly ok. – Joey Jan 08 '11 at 14:00