Click here to Skip to main content
13,768,110 members
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

46.1K views
19 bookmarked
Posted 25 Oct 2015
Licenced CPOL

Immutable objects in C#

, 25 Oct 2015
Rate this:
Please Sign up or sign in to vote.
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.

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.

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.

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.

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.

You can start from the below youtube video in which I have demonstrated design pattern with a full blown project.

License

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

Share

About the Author


You may also be interested in...

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 2:14
memberTecfield5-Sep-18 2:14 
SuggestionWord mistake: Use Setter instead of getter Pin
Trivedi Rishi23-Apr-17 22:49
professionalTrivedi Rishi23-Apr-17 22:49 
Suggestionless code using auto-implemented properties Pin
sx200827-Oct-15 9:57
membersx200827-Oct-15 9:57 
BugRe: less code using auto-implemented properties Pin
Matt T Heffron27-Oct-15 11:27
professionalMatt T Heffron27-Oct-15 11:27 
GeneralRe: less code using auto-implemented properties Pin
sx200827-Oct-15 12:20
membersx200827-Oct-15 12:20 
GeneralRe: less code using auto-implemented properties Pin
Shivprasad koirala27-Oct-15 16:46
mvpShivprasad koirala27-Oct-15 16:46 
GeneralRe: less code using auto-implemented properties Pin
mbb0127-Oct-15 23:17
membermbb0127-Oct-15 23:17 
AnswerRe: less code using auto-implemented properties Pin
sx200828-Oct-15 13:47
membersx200828-Oct-15 13:47 
GeneralRe: less code using auto-implemented properties Pin
kaos_1215-Nov-15 10:38
memberkaos_1215-Nov-15 10:38 
GeneralRe: less code using auto-implemented properties Pin
Tecfield5-Sep-18 2:07
memberTecfield5-Sep-18 2:07 
GeneralMy vote of 5 Pin
Fawad Raza27-Oct-15 7:25
memberFawad Raza27-Oct-15 7:25 
QuestionMy Vote 5 Pin
Amit Jadli26-Oct-15 2:55
professionalAmit Jadli26-Oct-15 2: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.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01-2016 | 2.8.181116.1 | Last Updated 26 Oct 2015
Article Copyright 2015 by Shivprasad koirala
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid