đź‘‹ Welcome to the channel everyone! Today we are diving into the fascinating world of immutability in C#. It may sound a bit fancy, but it's simply a way of creating objects that cannot be changed after they are created. Think of them like historical documents - once written, they stay that way. We'll cover immutable objects, immutable collections, and finally, records. So without further ado, let's get started!
Immutable Objects and Collections
In certain situations, you may require an object or collection that remains consistent throughout its lifecycle and cannot be altered after creation. This immutability ensures predictability and safety, as they can't be changed. Let's take a look at how they are implemented in code.
Immutable Objects
Imagine a class representing a person. Traditionally, you can change a person's name, but let's see how to make it immutable.
One solution is to initialize a field in the constructor and return that field. In this case, the property is read-only because there is no setter for that property, but you could have a method to change the person's name internally, which is not ideal for immutability.
public class Person
{
private string _name;
public Person(string name)
{
_name
}
public string Name => _name;
public void ChangeName(string newName)
{
_name = newName;
}
}
Using Read-Only Keyword
By using readonly
, we can initialize the field only once, ensuring that it can't be changed afterwards. However, this approach may involve a lot of code. Is there a simpler solution? The answer is "yes."
Using Init Keyword
We can use the init
keyword to initialize the property only once. This syntax is cleaner and more concise. Here’s a simple example:
public class Person(string name)
{
public string Name { get; init; } = name;
}
Records
Records, introduced in C# 9, are a special kind of class specifically designed for holding data. They come with immutability built right in, so you don’t have to worry about accidentally changing them. Plus, records automatically generate boilerplate code for things like equality checks, making your life a whole lot easier. They are perfect for scenarios like DTOs or configuration settings because they’re not supposed to change.
Here's how to create a record class for a person:
public record Person(string Name);
As you can see, it is much slimmer than the traditional class with the same properties. The only difference is that its record is immutable by default.
By using a record, a lot of boilerplate code is generated for us. For instance, it inherits from the IEquatable
interface, and we have a backing field for the Name
property along with additional code like Clone
.
Immutable Collections
Now, let's discuss immutable collections. Suppose we have an immutable collection of a person represented by a record. On the other hand, we have a mutable collection of a person that can be changed. How can we make it immutable?
Using IEnumerable
One approach is to convert it to an IEnumerable
, which does not have any add or edit methods, making it suitable for scenarios where only one iteration is needed. However, what can we do when we need to iterate over more than one item? In such cases, we can use IReadOnlyList
.
Using ImmutableList
IReadOnlyList
is perfect when you need a read-only collection and will not guarantee immutability! To make it immutable, we should use ImmutableList
. We can use the ToImmutableList
method to make the collection immutable. For example:
var list = new List<Person> { new Person("John"), new Person("Jane") };
var immutableList = list.ToImmutableList();
Even though the add method is available, it doesn't modify the existing list but creates a new one. here as the collection is immutable, the add method will work exactly like the with
keyword in Record and create a new instance of the collection.
Summary
That's the basic idea of immutable objects, records, and collections in C#. They might seem a bit different at first, but they offer a powerful way to write cleaner, safer, and more predictable code.
Join the Conversation!
I'd love to hear your thoughts! Have you used immutability in your projects? Share your experiences and opinions in the comments below.
Top comments (5)
Hello, I want to discuss about this topic with you.
Hey mate,
Sorry for the delayed response, I didn't receive any notification!
Of course, I'd be more than happy to catch up with you.
I used to develop the project using React and Node.js. But from last year I started to learn about the C# so as to become the .NET developer.
I am about to discuss this topic concerning the React, you agree with me?
Fab, welcome aboard mate! I will be publishing weekly C# tutorials here and on my YouTube channel. Don't forget to subscribe to stay updated!
Don't worry!