Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET stack and heap, what goes where when I declare a string?

Tags:

c#

.net

If I execute this line I create a string which is a reference.

string mystring = "Hello World"

Is variable mystring in the same context as the object I declare it? And the data "Hello World" on the heap?

like image 435
Simon Edström Avatar asked Oct 04 '12 12:10

Simon Edström


People also ask

Is string stored in heap C#?

Strings are reference types and their data is stored on the managed heap. By design, strings are immutable, which means that once created, their data cannot be modified.

What is stored on stack and heap in C#?

If the value type was declared as a method parameter then it's stored on the stack. If the value type was declared as a member of a class then it's stored on the heap, along with its parent. If the value type was declared as a member of a struct then it's stored wherever that struct is stored.

How are strings stored in memory C#?

String just implements an indexer of type char internally and we can say that string is just equivalent to char[] type with lots of extra code to make it useful for you, hence, like an array, it is stored on heap always.

Where are strings stored C#?

Both the string and the char[] are stored on the heap - so storage is the same.


3 Answers

Official Answer: it's an implementation detail and you don't need to know.

It is of course knowable for a specific (current) version of the framework:

1) if this is inside a method, then mystring is a reference variable, usually on the stack. But when it is captured, or when the method is async, or ... it is moved to the heap.

2) if this is inside a class, then each instance will contain a mystring reference as a field, stored on the heap.

In both cases there is an anonymous string object on the heap containing "Hello World"

like image 113
Henk Holterman Avatar answered Oct 03 '22 14:10

Henk Holterman


It's complicated. First of all the strings are interned by the compiler, so your string could be a reference to a previously allocated string object. Second of all it is an implementation detail, which you shouldn't worry about, and which can change at any of the next C#/.NET versions. I'll refer you to the excellent post by Eric Lippert, who is one of the people who write the C# compiler: here

like image 29
RA. Avatar answered Oct 03 '22 14:10

RA.


Read these... From Eric Lippert... he wrote the C# compiler! Should answer all your questions.

http://blogs.msdn.com/b/ericlippert/archive/2009/04/27/the-stack-is-an-implementation-detail.aspx

http://blogs.msdn.com/b/ericlippert/archive/2010/09/30/the-truth-about-value-types.aspx

like image 35
DRobertE Avatar answered Oct 03 '22 14:10

DRobertE