Programming Blog

Simple but potentially useful – A collection of random programming stuffs

Using the this Keyword

Posted by letmetutoryou on January 27, 2009

The this keyword implicitly refers to the object that is making an object method call.

In the following code, the statement name = name would have no effect at all. This is because the identifier name on the left side of the assignment does not resolve to the private BankAccount field called name. Both identifiers resolve to the method parameter, which is also called name.

class BankAccount

{

          private string name;

          public void SetName(string name)

         {

name = name;

         }

}

The C# compiler does not emit a warning for this bug.

Using the this Keyword

You can solve this reference problem by using the this keyword, as illustrated on the image. The this keyword refers to the current object for which the method is called. Static methods cannot use this as they are not called by using an object.

Changing the Parameter Name

You can also solve the reference problem by changing the name of the parameter, as in the following example:

class BankAccount

{

          private string name;

          public void SetName(string newName)

         {

name = newName;

}

}

Using this when writing constructors is a common C# idiom. The following code provides an example:

struct Time

{

          public Time(int hour, int minute)

         {

this.hour = hour;

this.minute = minute;

}

           private int hour, minute;

}

The this keyword is also used to implement call chaining. Notice in the following class that both methods return the calling object:

class Book

{

          private string author, title;

          public Book SetAuthor(string author)

         {

this.author = author;

return this;

          }

          public Book SetTitle(string title)

        {

this.title = title;

return this;

        }

}

Returning this allows method calls to be chained together, as follows:

class Usage

{

          static void Chained(Book good)

         {

good.SetAuthor(” Fowler”).SetTitle(” Refactoring”);

         }

        static void NotChained(Book good)

       {

good.SetAuthor(“Fowler”);

good.SetTitle(” Refactoring”);

       }

}

A static method exists at the class level and is called against the class and not against an object. This means that a static method cannot use the this operator.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.