CHAPTER 5 UNDERSTANDING ENCAPSULATION
}
driverIntensity = intensity;
}
Note Now that you better understand the role of class constructors, here is a nice short cut. The Visual Studio
IDE provides the ctor code snippet. When you type “ctor” and press the Tab key twice, the IDE will automatically
define a custom default constructor! You can then add custom parameters and implementation logic. Give it a try.
The Role of the this Keyword
C# supplies a this keyword that provides access to the current class instance. One possible use of the
this keyword is to resolve scope ambiguity, which can arise when an incoming parameter is named
identically to a data field of the class. Of course, ideally you would simply adopt a naming conventio n
that does not result in such ambiguity; however, to illustrate this use of the this keyword, update your
Motorcycle class with a new string field (named name) to represent the driver’s name. Next, add a
method named SetDriverName() implemented as follows:
class Motorcycle
{
public int driverIntensity;
// New
public
public
{
name
}
...
}
members to represent the name of the driver.
string name;
void SetDriverName(string name)
= name;
Although this code will compile just fine, Visual Studio will display a warning message informing
you that you have assigned a variable back to itself! To illustrate, update Main() to call SetDriverName()
and then print out the value of the name field. You might be surprised to find that the value of the name
field is an empty string!
// Make a Motorcycle with a rider named Tiny?
Motorcycle c = new Motorcycle(5);
c.SetDriverName("Tiny");
c.PopAWheely();
Console.WriteLine("Rider name is {0}", c.name); // Prints an empty name value!
The problem is that the implementation of SetDriverName() is assigning the incoming parameter
back to itself given that the compiler assumes name is referring to the variable currently in the method
scope rather than the name field at the class scope. To inform the compiler that you wish to set the
current object’s name data field to the incoming name parameter, simply use this to resolve the
ambiguity:
170