Share Blog

Monday, June 02, 2014

Difference between String and Stringbuilder in C#, Asp.net



String is immutable. Immutable means once we create string object we cannot modify. Any operation like insert, replace or append happened to change string simply it will discard the old value and it will create new instance in memory to hold the new value.

Example:
---------------------------------------------------------------------------------------------

string str = "hi";
// create a new string instance instead of changing the old one
str += "sunil";
str += "kumar";
---------------------------------------------------------------------------------------------
String Builder

String builder is mutable it means once we create string builder object we can perform any operation like insert, replace or append without creating new instance for every time.

Example:
------------------------------------------------------------------------------
StringBuilder sb = new StringBuilder("");
sb.Append("hi");
sb.Append("sunil");
string str = sb.ToString();
------------------------------------------------------------------------------


No comments:

Post a Comment