Executing Immutably

Immutability solves the shared data problem by not allowing data to be changed. If data can't be changed, there is no scope for a data race. If sequential execution means that you get the cake to yourself, immutability means that you can look at the cake but can't eat.

C# supports immutability with the readonly and const keywords. Fields marked with the const modifier must be declared and assigned in a single statement, such as this:

public const int AccountNumber = 123456;

Once declared and assigned, the const value cannot be changed, and the field can only be accessed through the type name, not an instance of the type. The readonly keyword is accessible through type instances and can be modified in a constructor; this means that the value of a readonly field can depend on which constructor is used to instantiate an immutable type. Listing 3-2 shows demonstrates both keywords in use.

Listing 3-2. An Immutable Bank Account using System;

namespace Listing_02 {

class ImmutableBankAccount {

0 0

Post a comment