Middle+
How are strings stored in .NET?
sobes.tech AI
Answer from AI
In .NET, strings are represented by the System.String type and are stored as a sequence of characters in memory in UTF-16 format (each character takes 2 bytes). Strings in .NET are immutable, meaning their contents cannot be changed after creation.
A string is stored in managed heap, contains its length and an array of characters. Due to immutability, strings are safe for multithreaded access without additional synchronization.
To modify strings, the StringBuilder class is used, which allows efficiently accumulating and modifying text without creating new string objects.
Example of creating and using a string:
string s = "Hello";
string s2 = s + " world"; // creates a new string
// For efficient modification:
var sb = new System.Text.StringBuilder();
sb.Append("Hello");
sb.Append(" world");
string result = sb.ToString();