This link?

Possible duplicate:
When do you use the keyword "this"?

Can someone explain me the link "this"? when do we use it? with a simple example.

+5
source share
4 answers

When you use thisinside a class, you are referring to the current instance: an instance of this 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, it this.firstNamerefers to the field of the firstNamecurrent instance of the class Person, and firstName(the right part of the destination) refers to the variable defined in the constructor area.

So when you do this:

Person me = new Person("Oscar", "Mederos")

thisrefers to an instance Personinstance me.

Edit:
this , .

this () , , : a[0], a["John"],...

+3

this - . , .

+3

Fluent APIs this. , .

0

public class AnObject
{
  public Guid Id { get; private set;}
  public DateTime Created {get; private set; }

  public AnObject()
  {
    Created = DateTime.Now;
    Id = Guid.NewGuid();
  }

  public void PrintToConsole()
  {
    Console.WriteLine("I am an object with id {0} and I was created at {1}", this.Id, this.Created); //note that the the 'this' keyword is redundant
  }
}

public Main(string[] args) 
{
  var obj = new AnObject();
  obj.PrintToConsole();
}
0

All Articles