- Back to Home »
- C#.NET »
- StringBuilder and string
Posted by :
Sudhir Chekuri
Monday, 22 February 2016
StringBuilder is mutable which means we can append, insert or replace text in string without creating new memory for it everytime. Once a StringBuilder is created text can be added to the existing text without creating new memory everytime whenever we are adding content to it. String Builder is under System.Text namespace. Append method is used to add text to the existing StringBuilder. Performance of StringBuilder is higher than string.
Output:
Hello world Second Line
Hello India Second Line for string
String
String is immutable which means once we create string object we cannot modify. Every time when you change the text using insert, replace or append methods new instance is created to hold the new value by discarding the old value. Performance of string is less than StringBuilder. String is under System namespace.
Example
program to use StringBuilder and string
using System;
using System.Text;
namespace Overriding
{
class Program
{
static void Main(string[] args)
{
// Create StringBuilder.
StringBuilder stringbuilder = new StringBuilder();
//Appending first line
stringbuilder.Append("Hello world ");
//Appending second line
stringbuilder.Append("Second Line");
//Printing text in StringBuilder
Console.WriteLine(stringbuilder);
//create string
string s;
//assign text to string
s = "Hello India ";
//append text to string
s +=
"Second Line
for string";
Console.WriteLine(s);
Console.ReadKey();
}
}
}
Output:
Hello world Second Line
Hello India Second Line for string