Skip to content

#10 String Builder

In OOPS string is an immutable object, i.e any updates to the string will result in creating new memory on the heap sometimes leading to memory issues.

Why are strings Immutable?

  • String are reference type object: so if a string is assigned to some other string variable then instead of creating a new value it will point to the same memory.
  • Cashing HashCode: languages use hashing to store strings as trying to search a string by name is time consuming compared to searching with an ID.
  • Security: As strings are not mutable they are used mainly to store network connections, open files, and so on.
  • Thread-safe: by default immutable objects are thread-safe, making sure that multiple threads don’t change the value of the string and we don’t end up needing to implement Synchronization

In those situations we could use String Builder

class Program
    static void Main(string[] args)
        //Creates a StringBuilder object passing a initial string
        //StringBuilder text = new StringBuilder();
        StringBuilder text = new StringBuilder("Hello World"); 

        //defining the max capacity of the string
        StringBuilder maxcapacity = new StringBuilder(5); 

        //Appending String
        maxcapacity.Append("What would happen when string exceed capacity");

        //Appending formated string
            text.AppendFormat("{0:C}", 12);

        //Inserting a new string at a location
        text.Insert(11, " Please pay: ");

Published inC#

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *