Looking for new “brainfood” on programming topics on the internet I came across a really interesting article about immutable types in C# from Joe Duffy who happens to be the lead developer and architect for Parallel Extensions to .NET. If an object of a given types is immutable that means that the state of the object will never change after being constructed. Joe Duffy explains and shows by example how immutable types could be approached in .NET
by following the five rules below:
- Immutable types must have only init only fields.
- Immutable types must only contain fields of immutable types.
- Immutable types should only subclass other immutable types.
- Mutable types should not subclass immutable types.
- Immutable types must not leak the ‘this’ reference during construction.
More information about immutable types in C# and the five rules above can be found in the following article: