Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the string type stored on the heap or the stack?

Here's what confuses me: in .NET, the string type is a class, but its behavior looks like it is a value type!

So is string a value type (stack memory) or a reference type (heap memory)?

like image 737
Ziad Salem Avatar asked Feb 28 '14 11:02

Ziad Salem


1 Answers

System.String is a reference-type. The value-like behaviour is actually what is called "immutablility", meaning that the object, once created, cannot be changed. All operations which you would expect to mutate the object (e.g. .ToUpper()) instead create a new instance.

Mutability is a separate topic from whether something is a reference-type or a value-type. You can have mutable value types (though they're considered a Bad Idea™).


To the issue of allocation, the simple answer is that reference types are normally allocated on the heap and value types are normally allocated on the stack.

In The Truth About Value Types, Eric Lippert explains how the CLR makes allocation decisions based more on the lifetime than anything else. Typically these are details that you don't need to worry about, but it's interesting information to have regardless.

like image 81
Paul Turner Avatar answered Oct 08 '22 14:10

Paul Turner