Information Technology Reference
In-Depth Information
// Almost immutable: there are holes that would
// allow state changes.
public struct PhoneList
{
private readonly Phone [] phones;
public PhoneList( Phone [] ph)
{
phones = ph;
}
public IEnumerable < Phone > Phones
{
get
{
return phones;
}
}
}
Phone [] phones = new Phone [ 10 ];
// initialize phones
PhoneList pl = new PhoneList (phones);
// Modify the phone list:
// also modifies the internals of the (supposedly)
// immutable object.
phones[ 5 ] = Phone .GeneratePhoneNumber();
The array class is a reference type. The array referenced inside the
PhoneList structure refers to the same array storage (phones) allocated
outside the object. Developers can modify your immutable structure
through another variable that refers to the same storage. To remove this
possibility, you need to make a defensive copy of the array. The previous
example shows the pitfalls of a mutable collection. Even more possibilities
for mischief exist if the Phone type is a mutable reference type. Clients
could modify the values in the collection, even if the collection is protected
against any modification. This defensive copy should be made in all con-
structors whenever your immutable type contains a mutable reference
type:
 
Search WWH ::




Custom Search