Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The this reference? [duplicate]

Tags:

c#

this

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

Can anyone explain me the "this" reference? when we use this ? with a simple example.

like image 418
billstep Avatar asked Apr 18 '11 13:04

billstep


1 Answers

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"],...

like image 63
Oscar Mederos Avatar answered Sep 22 '22 15:09

Oscar Mederos