Management of strings in structs

+1 to jjlin for a concise and accurate answer to the question, but a more general answer may be useful:

A field or variable declaration of any reference type represents a storage location for the reference. This is also true for fields of a struct.

(Including reference-type fields in a struct makes that type a "managed type", which is important in unsafe code; you can't declare a pointer to a managed type.)


The string itself is not stored in the struct. Instead a reference to the string is stored in the struct, so the struct size never changes.

string is not a value type; .NET strings are interned, which means that each unique string is stored in a look-up table in memory.


My first question to you would be, do your requirements dictate that a fixed length string is needed? If so a char[] might actually be what you are intending to use.

The .NET framework does not use C-style strings (char arrays) directly, but instead represents strings by immutable references. When a string is appended to or modified, you are actually creating a new string object in memory. This is a desired feature of the platform but one that requires consideration as expecting magically resizing strings can lead to some undesired side-effects.

Back to your question. "How does C# manage strings in structs?"

One of two ways to interpret this question from what I see:

1). How can I create structs that contain strings, and how does the .NET Framework manage strings in this scenario?

Short answer: keep in mind that strings are immutable types. Create your struct normally, and realize that the struct only contains a reference to the string, not a magically resizing segment of the struct that expands to include your volatile string.

2). How can the .NET Framework resize strings if they are a value type represented by structs.

Short answer, it doesn't. This isn't how .NET works with strings, see above.

Tags:

C#

String

Struct