Sobes.tech
Junior — Middle

How is the String data structure organized in memory?

sobes.tech AI

Answer from AI

In C#, a string (string) is an immutable object that is represented in memory as a sequence of characters in UTF-16 encoding.

The String data structure in memory includes:

  • An object in the managed heap, which contains:
    • An object header (metadata for garbage collection and type).
    • A field for the length of the string (number of characters).
    • A character array char[], where each character takes 2 bytes (UTF-16).

Since strings are immutable, any modification creates a new object, and the old one remains in memory until garbage collection.

Example:

string s = "Example";
// In memory, s holds an object with length 7 and a character array 'E','x','a','m','p','l','e'

Thus, a string is an object with a fixed length and a sequence of characters, optimized for safe and efficient use in .NET.