Information Technology Reference
In-Depth Information
avoiding code duplication, and constructor initializers generate much
more efficient object code. The C# compiler recognizes the constructor
initializer as special syntax and removes the duplicated variable initializ-
ers and the duplicated base class constructor calls. The result is that your
final object executes the minimum amount of code to properly initialize
the object. You also write the least code by delegating responsibilities to a
common constructor.
Constructor initializers allow one constructor to call another constructor.
This example shows a simple usage:
public class MyClass
{
// collection of data
private List < ImportantData > coll;
// Name of the instance:
private string name;
public MyClass() :
this ( 0 , "" )
{
}
public MyClass( int initialCount) :
this (initialCount, string .Empty)
{
}
public MyClass( int initialCount, string name)
{
coll = (initialCount > 0 ) ?
new List < ImportantData >(initialCount) :
new List < ImportantData >();
this .name = name;
}
}
C# 4.0 adds default parameters, which you can use to minimize the dupli-
cated code in constructors. You could replace all the different construc-
tors for MyClass with one constructor that specifies default values for all
or many of the values:
 
Search WWH ::




Custom Search