Tuesday, December 18, 2007

String - Reference or Value Type

In my interviews, I observed that 90% candidates don't have clear understanding of Reference or Value Types in .NET. I am not going to explain these two things here but want to clear one interesting point here.

Though String in .NET is Reference type object but it works as Value type.
Following code snippet will print "test"

static void Main(string[] args)

{

string str = "test";

ChangeString(str);

Console.WriteLine(str);

Console.ReadLine();

}

static void ChangeString(string str)

{

str += " Changed";

}





Following some line will better explain the things:
although strings are reference types, they work rather more like value types. When one string is set to the value of another, eg
string s1 = "hello";
string s2 = s1;

Then s2 does at this point reference the same string object as s1. However, when the value of s1 is changed, for instance with

s1 = "goodbye";

what happens is that a new string object is created for s1 to point to. Hence, following this piece of code, s1 equals "goodbye", whereas s2 still equals "hello".

The reason for this behaviour is that string objects are 'immutable'. That is, the properties of these objects can't themselves change. So in order to change what a string variable references, a new string object must be created.


No comments: