Lab 9 Mutable and Immutable Variables 20122021 050058pm

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 5

Lab 9: Mutability and immutability

Background

Mutable and immutable are English words that mean "can change" and "cannot change"
respectively. The meaning of these words is the same in C# programming language; that
means the mutable types are those whose data members can be changed after the instance
is created but Immutable types are those whose data members can not be changed after the
instance is created.

When we change the value of mutable objects, value is changed in same memory. But in
immutable type, the new memory is created and the modified value is stored in new
memory.

Let’s start with examples of predefined classes (String and StringBuilder).

String

Strings are immutable, which means we are creating new memory every time instead of
working on existing memory.

So, whenever we are modifying a value of the existing string, i.e., we are creating a new
object which refers to that modified string and the old one becomes unreferenced. Hence, if
we are modifying the existing string continuously, then numbers of the unreferenced object
will be increased and it will wait for the garbage collector to free the unreferenced object
and our application performance will be decreased.

Example 1

String s = "a";
s = s.concat("b"); // s+="b" and s=s+"b" also mean the same thing

Example 2 

1.             string str = string.Empty;  
2.   
3.             for (int i = 0; i < 1000; i++)  
4.             {  
5.                 str += "Modified ";  
11
6.             }   

In the code given above, string str will update 1000 times inside the loop and every time it
will create new instance so all old values will be collected by garbage collector after some
time.

It is not a good approach for this solution so, it’s better to go for mutable type. So in C#,
we have StringBuilder which is a mutable type. We have some advantages of immutable
classes like immutable objects are simpler to construct, test, and use. immutable objects are
always thread-safe and etc.

StringBuilder

StringBuilder is a mutable type, that means we are using the same memory location and
keep on appending/modifying the stuff to one instance. It will not create any further
instances hence it will not decrease the performance of the application.

Example 3

StringBuilder sb = new StringBuilder("a");


sb.append("b");

Example 4

1.             StringBuilder strB = new StringBuilder();  
2.   
3.             for (int i = 0; i < 10000; i++)  
4.             {  
5.                 strB.Append("Modified ");  
6.             }   

In the code given above, It has the huge impact of allocated memory because it will not
create instance each time.

We have many methods for modifying the StringBuilder String as below,

 Append - Appends information to the end of the current StringBuilder.


 AppendFormat - Replaces a format specifier passed in a string with formatted text.
 Insert - Inserts a string or object into the specified index of the current StringBuilder.
 Remove - Removes a specified number of characters from the current StringBuilder.
 Replace - Replaces a specified character at a specified index.

22
Example 5

String t = s;
t = t + "c";

StringBuilder tb = sb;
tb.append("c");

This shows that changing t had no effect on s, but changing tb affected sb too — possibly


to the surprise of the programmer. That’s the essence of the problem we’re going to look at
in this reading.
Since we have the immutable String class already, why do we even need the
mutable StringBuilder in programming? A common use for it is to concatenate a large
number of strings together. Consider this code:

String s = "";
for (int i = 0; i < n; ++i) {
s = s + n;
}

Using immutable strings, this makes a lot of temporary copies — the first number of the
string ("0") is actually copied n times in the course of building up the final string, the
second number is copied n-1 times, and so on. It actually costs O(n2) time just to do all that
copying, even though we only concatenated n elements.
StringBuilder is designed to minimize this copying. It uses a simple but clever internal data
structure to avoid doing any copying at all until the very end, when you ask for the
final String with a toString() call:

StringBuilder sb = new StringBuilder();


for (int i = 0; i < n; ++i) {
sb.append(String.valueOf(i));
}
String s = sb.toString();

Getting good performance is one reason why we use mutable objects. Another is
convenient sharing: two parts of your program can communicate more conveniently by
sharing a common mutable data structure.

Creating an Immutable Class

33
For creating an immutable class, we have to think about their properties or variables which
will never change the value(s) after assigning the first time. So, we are going to follow
some simple steps for creating the immutable class in C#.

Step 1

Make the variables read-only so we can not modify the variable after assigning the first
time. 

1. class MyClass  
2.     {  
3.         private readonly string myStr;          
4. }   

Step 2

Use parameterized constructor for assigning the myStr value for the class while creating
the object of the class as below 

1. class MyClass  
2.     {  
3.         private readonly string myStr;  
4.   
5.         public MyClass(string str)  
6.         {  
7.             myStr = str;  
8.         }  
9.     }   

Step 3

Use properties for getting the variables of the class and remove the setters of the property,
use only getters as below. 

1. class MyClass  
2.     {  
3.         private readonly string myStr;  
4.   
5.         public MyClass(string str)  
6.         {  
7.             myStr = str;  
8.         }  
9.   
10.         public string GetStr  
11.         {  
12.             get { return myStr; }  
13.         }  
14.     }   

In this easy way, we can create the immutable class in C#.

44
It is purely based on our project requirement which says it is better to use Mutable or
Immutable class.

Exercises
You have to design at-least 3 Mutable and immutable variables in coffee shop application.

55

You might also like