Re: Would a string instance become a value type if it was a member of a struct?
- From: Göran Andersson <guffa@xxxxxxxxx>
- Date: Thu, 18 Dec 2008 03:18:16 +0100
Sathyaish wrote:
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.
Well, that is not always true.
As a local variable the struct is stored on the stack.
As a member of an object the struct is stored as part of the object's data on the heap.
As part of another struct it will be stored as part of that struct's data, wherever that is stored.
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.
Actually any object's data also contains two references for internal use, and the String object probably also contains a length variable (so that you don't have to loop through the entire string each time you need to get the length).
My question:
Where would a string that is a member of a struct be stored?
struct foo
{
string bar;
}
foo f;
f.bar = "CoT";
The reference will be stored as part of the struct's data, wherever that is stored.
The string literal already exists as a constant in the assembly, so the reference will just point to that data.
If you would create a new string instance, e.g.:
f.bar = new String(new char[]{'C','o','T'});
then the string data would be stored on the heap.
--
Göran Andersson
_____
http://www.guffa.com
.
- References:
- Prev by Date: RE: System.Net.Mail.SmtpClient.Send() Error: An invalid character was found in the mail header.
- Next by Date: Re: Draw vertical text?
- Previous by thread: Re: Would a string instance become a value type if it was a member of a struct?
- Next by thread: RE: System.Net.Mail.SmtpClient.Send() Error: An invalid character was found in the mail header.
- Index(es):
Relevant Pages
|