this Keyword in C#
In C#, (this) keyword refers to the current instance of an object (in a nonstatic class; discussed later in the section Static Classes). In the earlier section on methods, we saw the use of this : Console.WriteLine(“{0} {1}”, this.FirstName, this.LastName); While the FirstName and LastName variable could be referenced without using the this keyword, prefixing them with it makes our code more readable, indicating that we are referring to an instance member.However, if instance members have the same names as our parameters, using this allows we to resolve the ambiguity: public void SetName(string FirstName, string LastName) { this.FirstName = FirstName; this.LastName = LastName; }
Another use of the this keyword is to pass the current object as a parameter to another method. For example: public class AddressBook { public void AddContact(Contact c) { Console.WriteLine(c.ID); Console.WriteLine(c.FirstName); Console.WriteLine(c.LastName); Console.WriteLine(c.Email); //---other implementations here--- //... } }
The AddContact() method takes in a Contact object and prints out the details of the contact. Suppose that the Contact class has a AddToAddressBook() method that takes in an AddressBook object. This method adds the Contact object into the AddressBook object: public class Contact { public int ID; public string FirstName; public string LastName; public string Email; public void AddToAddressBook(AddressBook addBook) { addBook.AddContact(this); } }
We use the this keyword to pass in the current instance of the Contact object into the AddressBook object in this case. To test out that code, use the following statements: Contact contact1 = new Contact(); contact1.ID = 12; contact1.FirstName = “Wei-Meng”; contact1.LastName = “Lee”; contact1.Email = “weimenglee@learn2develop.net”; AddressBook addBook1 = new AddressBook(); contact1.AddToAddressBook(addBook1);
|
No responses found. Be the first to respond and make money from revenue sharing program.
|