From the course: Advanced C#: Functional Programming Patterns

Principles of immutable types

- [Instructor] We've seen that using immutable types are beneficial. For example, they are thread safe and help prevent side effects. In this chapter, we'll look at the best way to create an immutable type in C Sharp. First, the definition. Put simply, immutable types, which are objects or data structures are types which are not changeable after creation. For.net types this means that they cannot change their internal state once they are initialized. In.net and other object-oriented languages, the simple explanation on how to make a class immutable as as follows. Make all the object properties or fields read-only. Set all the properties via the class constructors. This will work, the type will be immutable, but it can be awkward to use with this unsophisticated approach. Let's see what this would look like if we built a type on these two principles. For this example, I'll use the date-time structure in.net, which is an immutable type. So here I'm declaring two variables of date-time. And then because I have constructors that allow me to initialize the properties, I would call this constructor. Now the daytime has multiple constructors. I'm calling one of those constructors that takes three arguments the year, the month, and the day. So at this point after line 18, the state of the date-time structure is fixed I can't modify it. Now I can get the information from the date-time instance like this there's a day property. I can read that value. But if I were to try to change that value, uncomment this line. I'll get a compile error and the error is property or indexer DateTime.Day cannot be assigned to, it is read-only. So what if I wanted to add three days to the current date? What that would mean would look like is since the only way we can set the properties is via the constructor. I'd have to instantiate a new type, then take the existing year value and set that to the new date-time year, same thing here, take the month value and assign it the month and then take the current day value and add three to it and that's the new day that I store here. And in my example, I have one variable that has the original date-time and dt2 contains the new date-time. Now many of us would not bother to create this second variable. We can do something like this. Well, we reassign it back to the original variable. And this is allowed that not affecting the immutable type. The problem here is, is that there's only the constructors, the only way to set the values. So what we'll look at next is how to use some of the principles to make a better immutable type.

Contents