Executing immutably - C#. NET

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. This shows demonstrates both keywords in use.

An Immutable Bank Account

Immutability is not a widely used solution in C#, because not being able to change data values is a huge limitation. In Listing, 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.

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

C#. NET Topics