Reputation: 1066
I know that strings have variable length, therefore they need variable space in memory to be stored. When we define a string item in a struct
, the struct
's size would then be variable in length.
Older languages managed this by using fixed-length strings. However, there is no way to define fixed-length strings in C#, and C# manages normal strings in struct
s pretty good.
This becomes more weird when we define an array of such struct
s, or simply an array of strings. As result of any change (decrease/increase) in length of one string, all forward struct
s must be shifted.
How does C# handle variable-length strings in structs?
Upvotes: 38
Views: 27463
Reputation: 4703
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.
Upvotes: 61
Reputation: 11
Structure save in stack and string stores on heap.
Same as primitive types saves on stack and reference types saves on heap.
Upvotes: -7
Reputation: 43046
+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.)
Upvotes: 9
Reputation: 6685
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.
Upvotes: 15
Reputation: 5650
C# manages strings in structs the way it manages strings in general. See:
Upvotes: 4