Information Technology Reference
In-Depth Information
For example, the following code shows a constructor for class
MyDerivedClass
.
The constructor initializer specifies that the base class constructor to use is the one that
has two parameters; the first parameter is a
string
, and the second parameter is an
int
.
The parameters in the base parameter list must match the
intended constructor's
param-
eter list, in type and order.
Constructor initializer
↓
public MyDerivedClass( int x, string s ) : base( s, x )
{
↑
...
Keyword
When you declare a constructor without a constructor initializer, it is a shortcut for the
form with a constructor initializer consisting of
base()
, as illustrated in Figure 7-12. The two
forms are semantically equivalent.
Figure 7-12.
Equivalent forms of a constructor
Another form of constructor initializer instructs the constructor to use a different con-
structor in the same class. For example, the following shows a constructor for class
MyClass
,
which uses the constructor from the same class, but with two parameters, supplying a default
parameter as the second one.
Constructor initializer
↓
public MyClass(int x): this(x, "Using Default String")
{
↑
...
Keyword
}