Is string a reference type or a value type? Can anyone give a corresponding description?
views:
98answers:
3
+8
A:
string is an Immutable Reference Type. Below is a short example:
// All of these point to the same string in the heap
string hello = "Hello World!"; // creates string
string hello2 = "Hello World!"; // uses the previous string from the intern pool
string hello3 = hello2;
If you're looking for more information, check out Jon Skeet's post:
Justin Niessner
2010-08-11 15:06:03
+3
A:
System.String in the .net framework is a reference type, a very good explanation is that by Jon Skeet: C# in Depth: Strings in C# and .NET. The key points from his article are:
- It is a reference type
- It's immutable
- It can contain nulls
- It overloads the == operator
The last point is the one that makes string behave like a value type at times as you can write:
string s1 = "value";
string s2 = "value";
// result will be true.
bool result = (s1 == s2);
Rob
2010-08-11 15:08:22
@Rob: Actually that's an unfortunate example - string interning would make that true even without == overloading.
Jon Skeet
2010-08-11 17:59:09
@Jon - I'd forgotten about that - cantcha tell it was nearly hometime! :S
Rob
2010-08-11 18:22:23
A:
Check out the chapter Strings in C# and .NET by our very own master, John Skeet, from his book 'C# in Depth'. It tells you all you need to know.
Dan Diplo
2010-08-11 15:09:57