Possible Duplicate:
When do you use the “this” keyword?
Can anyone explain me the "this" reference? when we use this ? with a simple example.
When you use this
inside a class, you're refering to the current instance: to the instance of that class.
public class Person {
private string firstName;
private string lastName;
public Person(string firstName, string lastName) {
//How could you set the first name passed in the constructor to the local variable if both have the same?
this.firstName = firstName;
this.lastName = lastName;
}
//...
}
In the above example, this.firstName
is refering to the field firstName
of the current instance of the class Person
, and firstName
(the right part of the assignment) refers to the variable defined in the scope of the constructor.
So when you do:
Person me = new Person("Oscar", "Mederos")
this
refers to the instance Person
instance me
.
Edit:
As this
refers to the class instance, cannot be used inside static classes.
this
is used (too) to define indexers in your classes, like in arrays: a[0]
, a["John"]
,...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With