String Operations

String is immutable, which means it cannot be changed after it’s created. By assigning another value to the
string, it will create a new string object instead of updating the string at the same memory address.

So to modify the string either by appending text or change text etc. StringBuilder is a perfect choice.
C# provided StringBuilder under the System. Text namespace.

String Builder is a mutable one; it means the string value can be changed after it’s created using the same
object. It modifies the string using the helper methods like append, removes, etc. making it easy for string
manipulations.

Both String & String builders are reference types.

Example:

 

using System;
namespace SampleProgram {
  class MySample {
    public static void Main(string[] args) {
      StringBuilder sb = new StringBuilder(); //creation
      sb.Append( "Hello ! "); //concat string
      sb.Append( "How are you ? "); //concat string
      sb.Append( " Doing fine "); //concat string
      Console.WriteLine(sb);
      string str = "Hey";
      str = "Where are you from ? "; //string create new object
      //here,modification is not straight.
      Console.WriteLine(str);
    }
  }
}

 

The output will be:

Hello! How are you? Doing fine
Where are you from?

 

 

Related Tutorials