This Keyword is used To inform the compiler that you wish to
name data field to the incoming name parameter, simply use this to resolve
set the current object’s
the ambiguity:
public void SetDriverName(string name)
{ this.name = name; }
Chaining Constructor Calls Using this
Another use of the
this keyword is to design a class using a technique termed constructor chaining.
This design pattern is helpful when you have a class that defines multiple constructors. Given the
fact that constructors often validate the incoming arguments to enforce various business rules, it
can be quite common to find redundant validation logic within a class’s constructor set.
A cleaner approach is to designate the constructor that takes the
greatest number of arguments
as the “master constructor” and have its implementation perform the required validation logic. The
remaining constructors can make use of the
this keyword to forward the incoming arguments to
the master constructor and provide any additional parameters as necessary. In this way, we only
need to worry about maintaining a single constructor for the entire class, while the remaining constructors
are basically empty.
Here is the final iteration of the
Motorcycle class (with one additional constructor for the sake
of illustration). When chaining constructors, note how the
this keyword is “dangling” off the constructor’s
declaration (via a colon operator) outside the scope of the constructor itself:
class Motorcycle
{
public int driverIntensity;
public string driverName;
// Constructor chaining.
public Motorcycle() {}
public Motorcycle(int intensity)
: this(intensity, "") {}
public Motorcycle(string name)
: this(0, name) {}
// This is the 'master' constructor that does all the real work.
public Motorcycle(int intensity, string name)
{
if (intensity > 10)
{
intensity = 10;
}
driverIntensity = intensity;
driverName = name;
}
...
}
Observing Constructor Flow
On a final note, do know that once a constructor passes arguments to the designated master constructor
(and that constructor has processed the data), the constructor invoked originally by the
caller will finish executing any remaining code statements.
No comments:
Post a Comment