Immutable types in C#

Ever sat in a meeting with a bunch of devs and suddenly you hear the words ‘immutable type’ and your head explodes because what the heck is that?

It is a type of object whose data can’t be changed after its been instantiated. The string and Datetime classes are good examples.

If you weren’t aware, once you create a string, you cannot change its value.
The string class essentially creates a new string object internally for all string manipulation actions you perform.

The same goes for DateTime. When adding a month or day onto Datetime we are creating a new Datetime as opposed to modifying an old date.

Pros:

  • Thread Safety
  • Copying is fast and safe since the copy cant change either

Cons:

  • Slightly more effort required in implementing. Potentially in the form of a builder class that would apply the operations, although many times this isn’t an issue
  • Potential performance degrade when continuous changes are made (this would be more noticeable on objects that take up a lot of memory)

I have only summarised the very basics of Immutable types. My conclusion is use an immutable type for something that you know wont change.

Example: If you have a blob of text that is going to be displayed as a message and never change then use the string class. If you have a piece of text that you know you need to modify a lot then use the StringBuilder class instead.

Photo by Kristen Sturdivant