String vs. StringBuilder

Well some juniors told me that they have started C# so they want me to start some beginner level discussion on C# .NET

The first thing that came in my mind for novice was comparison between string and string builder class.

I don’t know whether you have noticed it or not.

In C# .NET strings are immutable and hence it also do not allow us to change it.

By immutable i mean, whenever we change the string it will create a new instance of it in memory rather than changing value on same memory location.

Let me clear this with the help of code.

Consider following code snippet :

string str= “Immutable”; //line 1
str += ” Test”; //line 2

when i appended ” Test” in str (in line 2), rather than appending it in the same instance, it will create another instance (somewhere else in memory) with value “Immutable Test” and str will now refer to “Immutable Test” in memory leaving the old one in memory unreferred for garbage collector.

It means that whenever we will change string, the .net framework will create a new one at any other place in the memory.

Plus because of this you are not allowed to change any string like
str[1]= ‘c’; because of immutability…

For the required behavior StringBuilder class is used.

String is faster than StringBuilder

thats all i want to say right now… Please correct me if i m wrong somewhere…

bye for now and keep saying

.NET Rocks :p