Public Immutable BankAccount Balance

class Listing_02 {

static void Main(string[] args) {

// create a bank account with the default balance ImmutableBankAccount bankAccount1 = new ImmutableBankAccount(); Console.WriteLine("Account Number: {0}, Account Balance: {1}", ImmutableBankAccount.AccountNumber, bankAccountl.Balance);

// create a bank account with a starting balance ImmutableBankAccount bankAccount2 = new ImmutableBankAccount(200); Console.WriteLine("Account Number: {0}, Account Balance: {1}", ImmutableBankAccount.AccountNumber, bankAccount2.Balance);

// wait for input before exiting Console.WriteLine("Press enter to finish"); Console.ReadLine();

Immutability is not a widely used solution in C#, because not being able to change data values is a huge limitation. In Listing 3-2, we ended up with a bank account whose balance can be read but not changed. Immutability is useful, however, for creating a clear separation between immutable reference data that can be safely shared between Tasks and mutable Task data that must be protected using a different technique.

■ Tip See the "Unexpected Immutability" example in the "Understanding Common Problems and Their Causes" section at the end of this chapter for an example of how misusing immutability can cause problems.

0 0

Post a comment