Introduction
Immutable objects are those objects in which once data has been loaded, it cannot be modified any way, internally or externally.
What kind of scenario immutable objects are prepared to use
An immutable object is used where ever data is static. For example, when master data is loaded into memory we don’t want to change it. For example, currency master, state master, etc.
In order to make a class immutable, it is a 3-step process.
Data should not be changed externally, so remove the setter in the class.
- Class state
- {
- private string _statename;
- Public string statename
- {
- Get {return _statename;}
- Set{_ statename =value }
- }
- }
By removing the setter, one doubt will come to mind: How do we set the value to class properties?
So what we will do is, we will go and create the constructor, via this constructor during the object initialization we will go and pass the data.
Create constructor and initialize the data.
- Public state(string name)
- {
- _ statename=name;
- }
Let's pass the data to the class by creating the object.
- Static void Main(string[] args)
- {
- State stateobj=new state(“Karnataka”);
- Stateobj. Statename=”Goa”;
- }
In the above code snippet, we can observe that I have tried assigning the data using the object but the compiler will throw an error. Why? Because we have removed the setter in class.
But internally some logic can modify the data by using the object. This can be avoided by making variable read-only.
Declare a variable as read-only.
- Private readonly string _ statename;
Finally summarizing the 3 steps:
- Go ahead and remove the setters.
- Create a constructor for loading the data.
- Make it variable as read-only
Summary
In this blog, we have discussed the life cycle of immutable objects.