Information Technology Reference
In-Depth Information
// Create an address:
Address2 a2 = new Address2 ( "111 S. Main" ,
"" , "Anytown" , "IL" , 61111 );
// To change, re-initialize:
a2 = new Address2 (a1.Line1,
a1.Line2, "Ann Arbor" , "MI" , 48103 );
The value of a1 is in one of two states: its original location in Anytown, or
its updated location in Ann Arbor. You do not modify the existing address
to create any of the invalid temporary states from the previous example.
Those interim states exist only during the execution of the Address con-
structor and are not visible outside that constructor. As soon as a new
Address object is constructed, its value is fixed for all time. It's exception
safe: a1 has either its original value or its new value. If an exception is
thrown during the construction of the new Address object, the original
value of a1 is unchanged.
This second Address type is not strictly immutable. Implicit Properties
with private setters can still contain methods that change the internal state.
If you want a truly immutable type, you would need to make further
changes. You need to change the implicit properties to explicit properties,
and change the backing field to a readonly field of the type:
public struct Address3
{
// remaining details elided
public string Line1
{
get { return Line1; }
}
private readonly string line1;
public string Line2
{
get { return line2; }
}
private readonly string line2;
public string City
{
 
Search WWH ::




Custom Search