Lecture overview -- Keyboard shortcut: 'u'  Previous page: Objects and Classes -- Keyboard shortcut: 'p'  Next page: Visibility Issues -- Keyboard shortcut: 'n'  Lecture notes - all slides and notes together  slide -- Keyboard shortcut: 't'  Textbook -- Keyboard shortcut: 'v'  Help page about these notes  Alphabetic index  Course home  Page 20 : 29
Object-oriented Programming in C#
Classes and Objects
The current object - this

The latest receiver of a message is called the current object. This is the object on which the latest instance method has been called.

The current object in a C# program execution is denoted by the variable this

/user/normark/oop-csharp-1/sources/c-sharp/bank-account/bank-account-5/bank-account.csThe BankAccount - emphasizing this. This program is explained

This example shows two different uses of this. First, it may be necessary to get access to the current object as such. In the example it is necessary to add the current account to a list of accounts. The second use pertain to methods (and constructors). It is convenient to use the same name for both formal parameters of methods and instance variables of the surrounding class. To disambiguate these, this.x refers to the instance variable named x, and x refers to the local meaning of x.

/user/normark/oop-csharp-1/sources/c-sharp/bank-account/bank-account-6/bank-account.csThe BankAccount - A more radical use of this. This program is explained

In this example, any use of a member of the current object is prefixed with this. This is a more radical use of this, which highlights use of members in the current object in contrast to members in other objects.

  • this used for other related purposes in C#:

    • Reference to shadowed instance variables

    • Activation of another constructor

    • Definition of indexers

    • In definition of extension methods

 

Read more about the current object in the text book version of this material.