Click here to Skip to main content
15,884,298 members
Articles / Programming Languages / C#

Immutable objects in C#

Rate me:
Please Sign up or sign in to vote.
3.61/5 (23 votes)
25 Oct 2015CPOL3 min read 95.6K   20   12
In this article, we will explain about Immutable in C#.

Table of Contents

Introduction

There is a saying which goes “MAKE THE POT WHILE THE MUD IS WET”. Once Mud becomes dry, it cannot be changed. Immutable objects walk on similar lines. Once the object is created, it cannot be modified by any way.

What are Immutable Objects?

Immutable objects are objects which once loaded cannot be changed / modified by any way external or internal.

Where are Immutable Objects Used?

If I put it in one line, Immutable objects are used for data WHICH IS STATIC. Below are some of the instances of the same.

  • Master data: One of the biggest uses of immutable objects is to load master data. Master data like country, currency, region, etc. rarely change. So we would like to load master data once in the memory and then we do not want it to be modified.
  • Configuration data: All application needs configuration data. In the Microsoft world, we normally store these configuration data into Web.config or App.config file. Such kind of data is represented by objects and these data once loaded in the application memory will not change. It's again a good practice to make these kind of configuration data objects as immutable.
  • Singleton objects: In applications, we normally create singleton objects for shared static data. So if the shared data is not changing, it’s an awesome candidate for immutable objects. In case you are new to Singleton pattern, please refer to this article Singleton Pattern in C#.

How Can We Create Immutable Objects in C#?

Immutable objects can be created only from immutable classes. To create an immutable class is a three step process:

Step 1: Remove the setters of the class, only have getters.
The first step towards creating an immutable class is to remove the setters. As we said, values of a immutable class cannot be modified EXTERNALLY or INTERNALLY. So by removing the getters, any client who creates the object of this class cannot modify the data once loaded.

C#
class Currency
{
        private string _CurrencyName;
        public string CurrencyName
        {
            get { return _CurrencyName; }
        }
        private string _CountryName;
        public string CountryName
        {
            get { return _CountryName; }
        }        
}

Step 2: Provide parameters via constructor.

We have removed the getters so there is no way to load data in to the class. So to provide data, we need to create constructors with parameters via which we can pass data to the object. Below is the modified code for the same.

C#
class Currency
{
// property Code removed for clarity

        public Currency(string paramCurrencyName,
                        string paramCountryName)
        {
            _CurrencyName = paramCurrencyName;
            _CountryName = paramCountryName;
        }
}

Step 3: Make the variables of the property READONLY

As we said in the previous definition, immutable objects cannot be modified by ANY WAY once the data is loaded. I will go one step further and say it cannot be modified EXTERNALLY by client or INTERNALLY by the class code himself.

But if you see our currency class, the variables can be modified after the object creation. In other words, see the below class code. We have created a method in the class called as “SomeLogic”. This method is able to successfully modify the variables after the object has been created.

C#
class Currency
{
        private string _CountryName;

        public string CountryName
        {
            get { return _CountryName; }
        }

        public void SomeLogic()
        {
            _CountryName = "I can not change this";
        }
}

So the solution for the above to make the variables “READONLY”. Below is the currency class modified where the property variables are made readonly. Readonly variables can be only initialized in the constructor and later they cannot be modified.

C#
class Currency
    {
        private readonly string _CurrencyName;

        public string CurrencyName
        {
            get { return _CurrencyName; }
        }
        private readonly string _CountryName;

        public string CountryName
        {
            get { return _CountryName; }
        }
        public Currency(string paramCurrencyName,
                        string paramCountryName)
        {
            _CurrencyName = paramCurrencyName;
            _CountryName = paramCountryName;
        }
    }

Hope you enjoyed this short note on Immutable objects. Immutable objects is a design pattern which was first officially discussed in Java concurrency in practice book. In case you are interested to learn design pattern, I would suggest creating a full blown project and starting implementing design pattern in the same.

For Further reading do watch  the below interview preparation videos and step by step video series.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect https://www.questpond.com
India India

Comments and Discussions

 
QuestionHow did this fetch any votes at all? Do people understand what immutable means at all in the first place? Pin
Tecfield5-Sep-18 1:14
Tecfield5-Sep-18 1:14 
SuggestionWord mistake: Use Setter instead of getter Pin
Trivedi Rishi23-Apr-17 21:49
professionalTrivedi Rishi23-Apr-17 21:49 
Suggestionless code using auto-implemented properties Pin
sx200827-Oct-15 8:57
sx200827-Oct-15 8:57 
BugRe: less code using auto-implemented properties Pin
Matt T Heffron27-Oct-15 10:27
professionalMatt T Heffron27-Oct-15 10:27 
GeneralRe: less code using auto-implemented properties Pin
sx200827-Oct-15 11:20
sx200827-Oct-15 11:20 
GeneralRe: less code using auto-implemented properties Pin
Shivprasad koirala27-Oct-15 15:46
Shivprasad koirala27-Oct-15 15:46 
GeneralRe: less code using auto-implemented properties Pin
mbb0127-Oct-15 22:17
mbb0127-Oct-15 22:17 
AnswerRe: less code using auto-implemented properties Pin
sx200828-Oct-15 12:47
sx200828-Oct-15 12:47 
GeneralRe: less code using auto-implemented properties Pin
kaos_1215-Nov-15 9:38
professionalkaos_1215-Nov-15 9:38 
GeneralRe: less code using auto-implemented properties Pin
Tecfield5-Sep-18 1:07
Tecfield5-Sep-18 1:07 
GeneralMy vote of 5 Pin
Fawad Raza27-Oct-15 6:25
Fawad Raza27-Oct-15 6:25 
QuestionMy Vote 5 Pin
Amit Jadli26-Oct-15 1:55
professionalAmit Jadli26-Oct-15 1:55 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.