C# StringBuilder

C# StringBuilder
String is immutable.

 
Meaning is every time you use methods in System.String class, you create a new instance of String class in a memory.
Creating new instances in memory for appending the string is costly and it consumes memory.

The System.Text.StringBuilder is a class which can modify String without creating new instance of string in memory.

using System.Text;

   protected void Button1_Click(object sender, EventArgs e)
    {
        StringBuilder sb = new StringBuilder("This is default constructor string ");
        string firstName = " MyName ";
        string lastName = " MyLastName ";
        sb.Append(firstName);
        sb.Append(lastName);
        Response.Write( sb.ToString() );
    }

OutPut:
This is default constructor string MyName MyLastName


Description:
Here sb is only one instance and we are not creating new instances for concatinating the two or many strings.
Also, you can clear the sb by calling Clear method of it

sb.Clear();

Tags:

C# foreach loopc# stringc# arraylistC# DateTime DifferenceC# XML XmlReaderC# Regular Expression Get Text Between BracketsC# Binary To StringC# For LoopReplace string in C#C# StopWatchC# Break Statement

Author

My name is Satalaj, but people call me Sat. Here is my homepage: . I live in Pune, PN and work as a Software Engineer. I'm former MVP in ASP.net year 2010.
Disclaimer: Views or opinion expressed here are my personal research and it has nothing to do with my employer. You are free to use the code, ideas/hints in your projects. However, you should not copy and paste my original content to other web sites. Feel free to copy or extend the code.
If you want to fight with me, this website is not for you.
 

I'm Satalaj.