Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is string a value type or a reference type?

Is string a value type or a reference type?

I just can't find a "good" explanation for this...

like image 428
Schwertz Avatar asked Jul 01 '09 13:07

Schwertz


People also ask

Why is String not a value type?

Strings aren't value types since they can be huge and need to be stored on the heap. Value types are stored on the stack as in the CLR implementation by Microsoft. Stack allocating strings would break all sorts of things.

Is String reference type or value type in Javascript?

@EnricoMassone yup - string literals are "value types", the result of new String() is a reference type.

Is string a reference variable?

Strings are Reference/Complex Object Type When you assign a string variable to another variable, It actually copies the reference to the object but not the object itself. It means, since the string variable holds the reference to the actual data, so it passes this reference and not the actual data.

Is string a value type in Java?

String is not a value type in either language, so in this way it's not a primitive. If by "primitive" you mean built into the language, then String is a primitive. It just uses a capital letter. String literals (those things in quotes) are automatically converted to System.


1 Answers

Console.WriteLine(typeof(string).IsClass); // true 

It's a reference type.

It can't be a value-type, as value-types need a known size for the stack etc. As a reference-type, the size of the reference is known in advance, even if the size of the string isn't.

It behaves like you expect a value-type to behave because it is immutable; i.e. it doesn't* change once created. But there are lots of other immutable reference-types. Delegate instances, for example.

*=except for inside StringBuilder, but you never see it while it is doing this...

like image 175
Marc Gravell Avatar answered Oct 09 '22 01:10

Marc Gravell