Information Technology Reference
In-Depth Information
// Call the third constructor, shown below.
this (initialCount, "" );
}
public MyClass( int initialCount, string Name)
{
// Instance Initializers would go here.
object (); // Not legal, illustrative only.
coll = (initialCount > 0 ) ?
new List < ImportantData >(initialCount) :
new List < ImportantData >();
name = Name;
}
}
The difference is that the compiler does not generate multiple calls to the
base class constructor, nor does it copy the instance variable initializers
into each constructor body. The fact that the base class constructor is called
only from the last constructor is also significant: You cannot include more
than one constructor initializer in a constructor definition. You can dele-
gate to another constructor in this class using this() , or you can call a
base class constructor using base() . You cannot do both.
Still don't buy the case for constructor initializers? Then think about read-
only constants. In this example, the name of the object should not change
during its lifetime. This means that you should make it read-only. That
causes the common utility function to generate compiler errors:
public class MyClass
{
// collection of data
private List < ImportantData > coll;
// Number for this instance
private int counter;
// Name of the instance:
private readonly string name;
public MyClass()
{
commonConstructor( 0 , string .Empty);
}
 
Search WWH ::




Custom Search