Difference between string and StringBuilder in C#

Both string and StringBuilder are used to store the data which is string type. But there are some differences between these two, today we discuss about the differences between string and StringBuilder. 

 1.       string is a data type which belongs to System namespace whereas StringBuilder is the class belongs to System.Text namespace.

 2.       string is immutable type means once create the string object you cannot modify that object. StringBuilder is the mutable object, that means after creation of object also you can change the object.

 3.       If you are modifying the string variable means, you are removing the exists variable from memory and creating new one. 

       For example consider below example. Here we create string variable str1 with some value. Initially it has one address, after every modification on this variable the variable address is changing.     

string str1 = "This is string data type";              

//Address is changing       
str1 = str1 + " example";      

//again Address is changing      
str1 = str1 + " which is immutable";

Other hand if you are modifying the StringBuilder object, you are not changing its address instead of that it will change only value. That means whatever address is there initially when you are creating the object is going to be there even though you are going to change value as shown below.         

StringBuilder sb = new StringBuilder();          
sb.Append("This is stringbuilder object");             

//Address is not changing            
sb.Append(" example");           

//again Address is not changing            
sb.Append(" which is mutable");

4.       Performance wise as compared with string, StringBuilder is fast because every time string is going to change its address whereas StringBuilder not. 

 5.       To decide whether to use string or StringBuilder, if you have less data modifications use string variable or if you have more data modifications use StringBuilder. You have to create the object to use StringBuilder. So use StringBuilder whenever you have more data modifications because it is costly as compared with string in terms of memory.