Information Technology Reference
In-Depth Information
public class MyClass
{
// collection of data
private List < ImportantData > coll;
// Name of the instance:
private string name;
// Needed to satisfy the new() constraint.
public MyClass() :
this ( 0 , string .Empty)
{
}
public MyClass( int initialCount = 0 , string name = "" )
{
coll = (initialCount > 0 ) ?
new List < ImportantData >(initialCount) :
new List < ImportantData >();
this .name = name;
}
}
There are tradeoffs in choosing default parameters over using multiple
overloads. (See Item 10.) Default parameters create more options for your
users. This version of MyClass specifies the default value for both param-
eters. Users could specify different values for either or both parameters.
Producing all the permutations using overloaded constructors would
require four different constructor overloads: a parameterless constructor,
one that asked for the initial count, one that asked for the name, and one
that asked for both parameters. Add more members to your class, and the
number of potential overloads grows as the number of permutations of all
the parameters grows. That complexity makes default parameters a very
powerful mechanism to minimize the number of potential overloads that
you need to create.
Defining default values for all parameters to your type's constructor means
that user code will be valid when you call the new MyClass(). When you
intend to support this concept, you should create an explicit parameterless
constructor in that type, as shown in the example code above. While most
code would default all parameters, generic classes that use the new() con-
straint will not accept a constructor with parameters that all have default
 
Search WWH ::




Custom Search