Re: Would a string instance become a value type if it was a member of a struct?
- From: "Anthony Jones" <AnthonyWJones@xxxxxxxxxxxxxxxx>
- Date: Wed, 17 Dec 2008 22:58:18 -0000
"Sathyaish" <sathyaish@xxxxxxxxx> wrote in message news:edd93470-3c83-4907-b58b-caaaa27ee13a@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
And I've probably asked this, like, a thousand times.
In .net, a struct is a value type, so it gets stored on the stack.
struct foo
{
int a;
byte b;
}
In the above code, both variables, a and b, would get stored on the
stack. Therefore, the sizeof(foo) would be 5 bytes (or 8 bytes
depending on compiler switches that govern padding and byte alignment.
In .net, this would be the StructLayoutKindAttribute)
But that's beside the point. Let me get to my question.
In .net, a string is a reference type. So:
string bar = "CoT"; //Unicode encoding by default
would mean bar (4 bytes) on the stack that reference 8 bytes (2*
(3+'\0')) on the heap.
My question:
Where would a string that is a member of a struct be stored?
struct foo
{
string bar;
}
foo f;
f.bar = "CoT";
A string is a reference type. The struct above would remain the same very small size regardless of how big the string is.
The string is allocated on the heap and then all things assigned from it would just point at that instance of the string.
foo f;
f.bar = "CoT";
foo g;
g.bar = f.bar
There is only one instance of a string containing "CoT" allocated somewhere in memory. Both f and g will contain references to this same instance.
--
Anthony Jones - MVP ASP/ASP.NET
.
- Follow-Ups:
- References:
- Prev by Date: Re: Dynamically adding Sql type to a parameter
- Next by Date: Re: Suggestion for C# language: Modification to the "new" keyword - Allow type inference in C# to use the left-hand side of the assignment
- Previous by thread: Would a string instance become a value type if it was a member of a struct?
- Next by thread: Re: Would a string instance become a value type if it was a member of a struct?
- Index(es):
Relevant Pages
|