0

Possible Duplicate:
When do you use the “this” keyword?

Hi All,

I am just wondering when and where using the keyword is a MUST? Because sometimes if I dont "this" or even I delete "this" the program just runs fine. So what will happen if you dont use it? or if you USE it in a wrong place.

Some explict examples would be appriciated.

Community
  • 1
  • 1
Dumbo
  • 13,555
  • 54
  • 184
  • 288

8 Answers8

3

The this keyword is often used to disambiguate between member variables and local variables:

...
{
    int variable = 10;

    this.variable = 1; // modifies a member variable.

    variable = 1; // modifies the local variable.
}
....

The other use of this is to pass a reference to the current object so:

....
DoSomethingWithAnObject( this );
....

Another use (Thanks to HadleyHope ) is to disambiguate when method parameters are assigned to member variables with the same name:

void Initialise( int variable )
{ 
    this.variable = variable;
}
Community
  • 1
  • 1
Nick
  • 25,026
  • 7
  • 51
  • 83
  • Used also to assign method parameters to member variables with the same name. – HadleyHope Mar 16 '11 at 09:10
  • 2
    I would also add there is a school of thought that recommends avoiding scope variable conflicts that require use of "this" to sort out, due to the potential confusion it can cause. I tend to use it myself on a strict short-term basis - e.g. on constructors, it is harmless when all you're going to do is write "this.liveStatus = liveStatus" – Joel Goodwin Mar 16 '11 at 09:10
1

You can't use this when calling static members. The compiler will just not let you. When you use "this" you are explicitly calling the current instance. I like to prefix current instance members with "this" even if this is not mandatory but just for clarity. That way I distinguish local scope variables from members.

Cheers

Fabian Nicollier
  • 2,811
  • 1
  • 23
  • 19
1
public class People{
    private String name;
    private int age;
    public People(String name, int age){
        this.name = name;
        this.age = age; //use this to declare that the age is the field in People class 
    }
}

One way to use this, hope it can help you.

Waldheinz
  • 10,399
  • 3
  • 31
  • 61
Danyun Liu
  • 3,072
  • 24
  • 22
1

Microsoft recommend using camelCase for member variables, i.e.

public class MyClass
{
     private int myInt;

     private void SetMyInt(int myInt)
     {
          this.myInt = myInt;
     }
}

So if you didn't have the 'this' keyword, there would be confusion between the private member and the parameter.

Personally I prefer prefixing my private members with an underscore to avoid this confusion.

private int _myInt;

So the only real use I find for it is to pass a reference of the current object to something else

MyStaticClass.MyStaticMethod(this);
David Masters
  • 8,069
  • 2
  • 44
  • 75
0

You don't have to use "this" keyword every time in your member method, it is useful in this case:

class human
{
    private int age;
...
    void func(int age)
    {
       this.age = age;
    }
...
}

it can solve the confusion which age you mean

ruisen
  • 31
  • 5
0

You can use this when you have a member variable and a local variable of the same name in the same scope - the "this" will then make clear which one you mean.

Consider this:

class Person
{
    private string name;

    public string Name
    {
        get
        {
            return name;
        }
        set
        {
            name = value;
        }
    }

    public Person(string name)
    {
        this.name = name;   // "this" is necessary here to disambiguate between the name passed in and the name field.
        this.Name = name;   // "this" is not necessary, as there is only one Name in scope.
        Name = name;        // See - works without "this".
    }
}
Polyfun
  • 9,479
  • 4
  • 31
  • 39
0

Personally I use this whenever I'm accessing a member variable or method. 99% of the time it's not necessary, but I think it improves clarity and makes the code more readable - a quality well worth the extra effort of typing 4 characters and a dot.

MattDavey
  • 8,897
  • 3
  • 31
  • 54
0

This is a bit subjective, but if you are using a proper naming convention (I use _camelCase for member variables) you will never need to use this.

Except this exception: =)

When you want to call an extension method from inside the class that the extension method is for:

public class HomeController : Controller
{

    public ActionResult Index()
    {
        // won't work
        return MyCustomResult();
    }

    public ActionResult List()
    {
        // will work
        return this.MyCustomResult();
    }
}

public static class MyExtensions
{
    public static MyResult MyCustomResult(this Controller instance)
    {
         return new SomeResult(instance.ActionName);
    }
}
jgauffin
  • 99,844
  • 45
  • 235
  • 372