tags:

views:

98

answers:

3

Is string a reference type or a value type? Can anyone give a corresponding description?

+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:

C# in Depth: Strings in C# and .NET

Justin Niessner
+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
@Rob: Actually that's an unfortunate example - string interning would make that true even without == overloading.
Jon Skeet
@Jon - I'd forgotten about that - cantcha tell it was nearly hometime! :S
Rob
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