Possible Duplicate:
When do you use the “this” keyword?
Hello,
I understand that the This keyword is used to refer to an instance of the class, however, suppose I have a class called Life, which defines two fields, the person (their name) and their partner(their name):
class Life
{
//Fields
private string _person;
private string _partner;
//Properties
public string Person
{
get { return _person; }
set { _person = value; }
}
public string Partner
{
get { return _partner; }
set { _partner = value; }
}
//Constructor 1
public Life()
{
_person = "Dave";
_partner = "Sarah";
MessageBox.Show("Life Constructor Called");
}
//Constructor 2
public Life()
{
this._person = "Dave";
this._partner = "Sarah";
MessageBox.Show("Life Constructor Called");
}
}
Is there a difference between constructor 1 and constructor 2!?
Or is it just better coding practice to use the “This” keyword?
Regards
The constructors are the same.
The reason I would prefer the second is that it will allow you to remove the underscores from your private variable names and retain the context (improving understandability). I make it a practice to always usethiswhen referring to instance variables and properties.I no longer use the
thiskeyword in this way after moving to a different company with different standards. I’ve gotten used to it and now rarely use it at all when referring to instance members. I do still recommend using properties (obviously).My version of your class:
or, even better, but not as clear about the use of
thiswith fields.