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: 5097 | Points: 40
Answer:

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());

sb.Append("eep");
Console.WriteLine(sb + " " + sb.GetHashCode());
}
}

/*output
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...

Regards
Akiii

Login to post response