Is string a value type or a reference type?
I just can't find a "good" explanation for this...
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.
@EnricoMassone yup - string literals are "value types", the result of new String() is a reference type.
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.
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.
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With