Question

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)?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top