This article provides an insight about immutable objects -- classes, data types etc. -- in C#. We will also the cover the differences between immutable and mutable types in C#.
Introduction
Anything that is immutable implies that it is read-only/static. To put it in simpler words, the value of the immutable types do not change over the course of execution.
Immutable Classes
To implement the concept of immutable classes, you can choose to have the properties of that class as public but with only "getter" methods defined. No setter for the properties should be available.
Other things to keep in mind while creating an immutable class:
- The member variables corresponding to the properties should be private.
- The class should implement a parameterized constructor through which the values of properties can be set.
Sample code below
- public class ImmutableClass
- {
- private string name;
- public string Name
- {
- get; //no setter defined
- }
- public ImmutableClass(string nameVal)
- {
- this.name = nameval;
- }
- }
String is one of the immutable data types that is available in C#. While string is a reference type (theoretically), it appears to behave like a value type. Whenever an append operation is performed on a string, it appears like the same object is updated but behind the screens it behaves in an entirely different way.
For every append operation performed, a new string object is created and the older is available for the garbage collector to collect. Hence, string in C# is immutable.
Sample code
- string dummy = "immutable";
- dummy += "String";
Hope this clarifies the "immutable types" in C#.
Difference between Immutable Types and Mutable Types
String is immutable and StringBuilder is mutable. To elaborate, when we use StringBuilder, the same object is used to hold the new value, unlike String.
Sample code for illustration
- StringBuilder sb = new StringBuilder("Hello");
- sb.Append("Hi");
Guest UserPosted Jun 16, 2016, 7:37 PM
maybe you can extend your blog and write an article, exploring other ways of immutability like const, static
Guest UserPosted Jun 16, 2016, 7:37 PM
nice one. C# allows you to declare truly immutable named fields with the const keyword.
Ram NunnaPosted Jun 16, 2016, 5:24 AM
nice
Vipul MalhotraPosted Jun 16, 2016, 3:25 AM
nice.
RajaPosted Jun 16, 2016, 3:04 AM
Nice Share....