tags:

views:

222

answers:

8

Duplicate

When do you use the “this” keyword?


What is the best practice case of referencing "this" in any given class?

Basic C# Forms example:

class SomeForm : Form
{
  public SomeForm() {
    Text= "Hey, I'm a new form.";
    Size= new Size(400,350);
    SetupButtons();
  }
  private void SetupButtons() {
    Button btn1= new Button();
    //...
    Controls.Add(btn1);
  }
  public static void Main() {
    Application.Run( new SomeForm() );
  }
}

vs:

class SomeForm : Form
{
  public SomeForm() {
    this.Text= "Hey, I'm a new form.";
    this.Size= new Size(400,350);
    this.SetupButtons();
  }
  private void SetupButtons() {
    Button btn1= new Button();
    //...
    this.Controls.Add(btn1);
  }
  public static void Main() {
    Application.Run( new SomeForm() );
  }
}
+1  A: 

This is personal preference. Do as you see fit or are comfortable with. I see no problems with either approach. I prefer to not use the this. keyword but this is up to you.

Ray Booysen
To keep my code clean most of the time I don't use "this". But using "this" really helps point where the variable's scope is.
Matthew Whited
I agree Matthew.
Ray Booysen
+1  A: 

This thread should answer your question.

Brandon
+2  A: 

The rule I've always followed is to always use this when the object is not declared within the same class and file. For your example I would use this since the controls you are referencing, while part of the class, are declared in the designer file.

I know some of my co-workers believe you should always use this for instances and the class name for statics.

Alexander Kahoun
Your co-workers are introducing visual noise that isn't needed. Slap them.
Nick Veys
A: 

In general, I omit using this unless

  • you're publishing a reference to this (obviously)
  • it's necessary to disambiguate in-scope variables (common in Java setters)
  • it clarifies that you're changing the state of the object somehow
Paul Morie
A: 

I usually use this if I create a derived class, I usually only use this. to reference things in the parent, otherwise I reference the global variables for the class normally (i.e. without this.)

Fry
+2  A: 

Sometimes, of course, it's required - to disambiguate between the instance variable and an identically named parameter, or to pass this as a parameter to something else.

When it's not required, I consider it codejunk, just noise on the page that detracts from the content. It is clutter, it gets in my way. I say: drop it when you don't need it.

Carl Manaster
A: 

I use this only when necessary (disambiguation or when I want to express my intentions more clearly).

It really depends on your preferences and naming conventions.

ppiotrowicz
A: 

I'm using it when I'm being lazy and want auto completion to come up for me. However I find 'this' to make the code more readable, it signals that the variable you are using is a class scope variable and should be handled with care.

Malfist