Introduction :
In this post i am going to explain the difference between String and String Builder in C#. This is a common interview question.
String
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.
Program
Using System;
public static void Main()
{
string myString = "Difference";
myString += " between";
myString += " String";
myString += " and";
myString += " StringBuilder";
}
public static void Main()
{
string myString = "Difference";
myString += " between";
myString += " String";
myString += " and";
myString += " StringBuilder";
}
StringBuilder
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.
Program
Using System.Text;
public static void Main()
{
StringBuilder myString = new StringBuilder("Difference");
myString.Append(" between")
myString.Append(" String")
myString.Append(" and")
myString.Append(" StringBuilder")
}
public static void Main()
{
StringBuilder myString = new StringBuilder("Difference");
myString.Append(" between")
myString.Append(" String")
myString.Append(" and")
myString.Append(" StringBuilder")
}
For better understanding see the below table and image
!********************* Hope you understand the difference J ***************************!
Reference:
http://www.aspdotnet-suresh.com & Venkat's csharp-video-tuotrials.blogspot.co.uk
No comments:
Post a Comment