Information Technology Reference
In-Depth Information
public MyClass( int initialCount)
{
commonConstructor(initialCount, string .Empty);
}
public MyClass( int initialCount, string Name)
{
commonConstructor(initialCount, Name);
}
private void commonConstructor( int count,
string name)
{
coll = (count > 0 ) ?
new List < ImportantData >(count) :
new List < ImportantData >();
// ERROR changing the name outside of a constructor.
this .name = name;
}
}
C++ programmers just live with this and initialize Name in all construc-
tors, or they cast away constness in the utility routine. C#'s constructor
initializers provide a better alternative. All but the most trivial classes con-
tain more than one constructor. Their job is to initialize all the members
of an object. By their very nature, these functions have similar or, ideally,
shared logic. Use the C# constructor initializer to factor out those com-
mon algorithms so that you write them once and they execute once.
Both default parameters and overloads have their place. In general, you
should prefer default values to overloaded constructors. After all, if you
are letting client developers specify parameter values at all, your con-
structor must be capable of handling any values that users specify. Your
original default values should always be reasonable and shouldn't gener-
ate exceptions. Therefore, even though changing the default parameter
values is technically a breaking change, it shouldn't be observable to your
clients. Their code will still use the original values, and those original val-
ues should still produce reasonable behavior. That minimizes the poten-
tial hazards of using default values.
This is the last item about object initialization in C#. That makes it a good
time to review the entire sequence of events for constructing an instance
 
Search WWH ::




Custom Search