Diffrence between string and strinbuilder in C#
String
1> Is an immutable.
2> Time taken.
3> No Append keyword used.
StringBuilder
1>Is mutable.
2>performance is high because use same instance of an object to perform actions.
3> Append Keyword used.
Example :- String
using System;
namespace Test_Application
{
class Program
{
static void Main(string[] args)
{
string str = "hi ";
str += "I ";
str += "am ";
str += "boy ";
Console.WriteLine(str);
Console.ReadLine();
}
}
}
Output:-
hi
hi I
hi I am
hi I am boy.
Example StringBuilder.
using System;
using System.Text;
namespace Test_Application
{
class Program
{
static void Main(string[] args)
{
StringBuilder str = new StringBuilder();
str.Append("I ");
str.Append("am ");
str.Append("boy ");
Console.WriteLine(str);
Console.ReadLine();
}
}
}
Output :-
I am boy
String
1> Is an immutable.
2> Time taken.
3> No Append keyword used.
StringBuilder
1>Is mutable.
2>performance is high because use same instance of an object to perform actions.
3> Append Keyword used.
Example :- String
using System;
namespace Test_Application
{
class Program
{
static void Main(string[] args)
{
string str = "hi ";
str += "I ";
str += "am ";
str += "boy ";
Console.WriteLine(str);
Console.ReadLine();
}
}
}
Output:-
hi
hi I
hi I am
hi I am boy.
Example StringBuilder.
using System;
using System.Text;
namespace Test_Application
{
class Program
{
static void Main(string[] args)
{
StringBuilder str = new StringBuilder();
str.Append("I ");
str.Append("am ");
str.Append("boy ");
Console.WriteLine(str);
Console.ReadLine();
}
}
}
Output :-
I am boy