Information Technology Reference
In-Depth Information
// Immutable: A copy is made at construction.
public struct PhoneList2
{
private readonly Phone [] phones;
public PhoneList2( Phone [] ph)
{
phones = new Phone [ph.Length];
// Copies values because Phone is a value type.
ph.CopyTo(phones, 0 );
}
public IEnumerable < Phone > Phones
{
get
{
return phones;
}
}
}
Phone [] phones2 = new Phone [ 10 ];
// initialize phones
PhoneList p2 = new PhoneList (phones);
// Modify the phone list:
// Does not modify the copy in pl.
phones2[ 5 ] = Phone .GeneratePhoneNumber();
Yo u n e e d t o f o l l o w t h e s a m e r u l e s w h e n y o u r e t u r n a m u t a b l e r e f e r e n c e
type. If you add a property to retrieve the entire array from the PhoneList
struct, that accessor would also need to create a defensive copy. See Item
27 for more details.
The complexity of a type dictates which of three strategies you will use to
initialize your immutable type. The Address structure defined one con-
structor to allow clients to initialize an address. Defining the reasonable set
of constructors is often the simplest approach.
Yo u c a n a l s o c r e a t e f a c t o r y m e t h o d s t o i n i t i a l i z e t h e s t r u c t u r e . F a c t o r i e s
make it easier to create common values. The .NET Framework Color type
 
Search WWH ::




Custom Search