From the course: Advanced C#: Functional Programming Patterns

Unlock this course with a free trial

Join today to access over 24,500 courses taught by industry experts.

More principles

More principles

Immutable types offer benefits like thread safety and predictability. However, applications require mutable data to perform needed operations. These competing goals can be reconciled. A common misconception about immutability is that it forbids change altogether. This isn't the case. While immutable types prevent direct modification of the original data, they don't stop change from happening. Instead, any change results in a new version of the data, leaving the original untouched. Instead, it's about how to handle change. Here's a diagram to help illustrate it. When we instantiate the immutable type, the properties are initialized. Now we can work with the immutable instance. It's impossible to change the values in this instance. To modify existing properties in an immutable type, create methods that return a new instance of the object with the updated values. For example, an AddDays() method would adjust the day value and return a new instance with the change applied, leaving the…

Contents