Information Technology Reference
In-Depth Information
MyClass2( int size)
{
labels = new List < string >(size);
}
}
When you create a new MyClass2, specifying the size of the collection, you
create two array lists. One is immediately garbage. The variable initializer
executes before every constructor. The constructor body creates the second
array list. The compiler creates this version of MyClass2, which you would
never code by hand. (For the proper way to handle this situation, see
Item 14.)
public class MyClass2
{
// declare the collection, and initialize it.
private List < string > labels;
MyClass2()
{
labels = new List < string >();
}
MyClass2( int size)
{
labels = new List < string >();
labels = new List < string >(size);
}
}
Yo u c a n r u n i n t o t h e s a m e s i t u a t i o n w h e n e v e r y o u u s e i m p l i c i t p r o p e r t i e s
(see Item 1). Your code does not have access to the compiler-generated
backing field, so you can't use an initializer for implicit properties. You
have no choice but to initialize data coded in implicit properties using con-
structors. Using implicit properties is still an advantage when you don't
have any validation logic in your data setters. If you migrate from an
implicit property to a named backing field with explicitly coded properties,
you should update the initialization code to initialize the data members
using initializers rather than constructor code. For those data elements
where implicit properties are the right choice, Item 14 shows how to min-
imize any duplication when you initialize data held in implicit properties.
 
Search WWH ::




Custom Search