why can you prove that string is immutable datatype while StringBuilder is Mutable Datatype ?

 Posted by Pradsir on 2/24/2011 | Category: C# Interview questions | Views: 3339 | Points: 40

Hi All

We can prove this by using Object.GetHashCode () Method provided in super class of all .net langues..

The hash code is a numeric value that is used to identify an object..

Please refer the below line of code..

using System;

using System.Text;

class Program
static void Main(string[] args)
string strtemp ="Prad";
Console.WriteLine(strtemp +" "+ strtemp.GetHashCode());

strtemp = strtemp + "eep";
Console.WriteLine(strtemp +" "+strtemp.GetHashCode());

StringBuilder sb = new StringBuilder("Prad");
Console.WriteLine(sb + " " + sb.GetHashCode());

Console.WriteLine(sb + " " + sb.GetHashCode());

Prad 432992021
Pradeep -673750172
Prad 46104728
Pradeep 46104728 */

As we can see for any operation performed on the string the new memory is created that y it is called immutable..

while for stringbuilder for all the operation the same memory is being modified.. as we can see the hashcode both time is same.

Happy coding :-)

Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Posted by: Akiii on: 6/9/2011 | Points: 10
excellent explanation...


Login to post response