Writing a constructor is a recurring task. Many developers write a constructor first, then copy and paste into other constructors to satisfy some of the overloaded interfaces of the class. I hope you didn't do that, if yes, stop it. Experienced C + + programs may use an auxiliary private method to construct objects in a common algorithm. Please stop it, too. When you find that multiple constructors contain the same logic, instead, place the logic in a common constructor. You can avoid the benefits of duplication of code, and constructor initialization is more efficient than executing other code of the object. The C # compiler recognizes the initialization of a constructor as a special syntax, and removes duplicate variables and duplicate base class constructors from the preset methods. The result is that your object eventually executes the least code to properly initialize the object. You can also write the fewest code to delegate responsibility to a commonly used constructor. The constructor's preset method allows one constructor to call another constructor. This is a simple example:
public class MyClass
{
// collection of data
private ArrayList _coll;
// Name of the instance:
private string _name;
public MyClass() :
this( 0, "" )
{
}
public MyClass( int initialCount ) :
this( initialCount, "" )
{
}
public MyClass( int initialCount, string name )
{
_coll = ( initialCount > 0 ) ?
new ArrayList( initialCount ) :
new ArrayList();
_name = name;
}
}
C # does not support parameters with default values, C + + is a good solution to this problem (C + + can make the parameters have default values, thereby effectively reducing the overload of the function). You must rewrite each of the special constructors. For such a constructor, it means that a lot of code repeats work. You can use a constructor chain to replace a regular method. Here are some of the general inefficiencies of the constructor logic:
public class MyClass
{
// collection of data
private ArrayList _coll;
// Name of the instance:
private string _name;
public MyClass ()
{
commonConstructor( 0, "" );
}
public MyClass( int initialCount )
{
commonConstructor( initialCount, "" );
}
public MyClass( int initialCount, string Name )
{
commonConstructor( initialCount, Name );
}
private void commonConstructor( int count,
string name )
{
_coll = (count > 0 ) ?
new ArrayList(count) :
new ArrayList();
_name = name;
}
}