Here, we will learn what is string c#, how to use string c#, what is stringbuilder in c#, and the differences between string and StringBuilder in c# with examples.
In c#, the string is useful to hold the sequential collection of characters and it can be defined by using
string keyword. The string is immutable which means the string object cannot be modified once it is created.
If you perform any operation like insert, update, delete, etc. on a string object, it will simply discard the old instance in the memory and create a new instance to hold the value.
In c#, we can define and initialize the values to string variables in different ways using
In this string example, we defined the string variables using
String keywords. Functionality wise both the keywords (
String) are same. Here, the
string keyword is an alias name for
To learn more about strings, check out our C# String with Examples topic.
In c#, the StringBuilder is same as the string to store the sequential collection of characters as text, but the only difference is the string is immutable, and the StringBuilder is mutable.
Mutability means once you create the StringBuilder instance in c#, the same instance will be used to perform any operation like insert, update, delete, etc. on the StringBuilder object. The StringBuilder class is available with
Following is the example of defining and adding values to the StringBuilder in c#.
To learn more about StringBuilder, check out StringBuilder in C# with Examples.
As discussed, the string and StringBuilder are useful to hold or store the collection of characters. The following table lists the differences between string and StringBuilder in c#.
|The string is useful for storing the sequential collection of characters.||The StringBuilder is same as a string to store the collection of characters.|
|The string is available with System.String type.||The StringBuilder is available with System.Text type.|
|The string is immutable and it cannot be modified once it is created.||The StringBuilder is mutable and it can be modified after creation.|
|The string performance is almost same as StringBuilder. For a fixed number of operations, it is always advisable to use string.||Compared to string, the StringBuilder performance is slightly better when you perform a large number of modify operations on string otherwise it's negligible.|