This article analyzes the difference between string and StingBuilder in C# for example, which helps to better grasp the usage of string and StingBuilder in C# programming. Share it for your reference. The specific methods are as follows:
For the difference between string and StringBuilder, refer to MSDN. This article uses programs to demonstrate their differences in memory and therefore their behavior differently.
Let’s take a look at the following code:
//Example: string's memory modelnamespace ConsoleApplication2 { class Program { static void Main(string[] args) { string a = "1234"; string b = a;//a,and b point to the same address (a); (b); a = "5678"; (a); (b);//That b's value is not changed means string's value cann't be changed (); } } }
Output:
1234
1234
5678;change a's value,b's value is not changed
1234
//Example: StringBuilder's memory modelnamespace ConsoleApplication3 { class Program { static void Main(string[] args) { StringBuilder a = new StringBuilder("1234"); StringBuilder b = new StringBuilder(); b = a; (); ("5678"); (a); (b); (); } } }
Output:
5678
5678
I hope this article will be helpful to everyone's C# programming.