The secret to understanding how .NET technologies works is to understand the why behind it.This blog tries to answer the Why! Why classes , objects , technologies in .NET were designed the way they are ?

Tuesday, December 29, 2009

Is String a value type or a reference type in .NET

This is a typical interview question that is asked to developers

Is String a value type or a reference type  in .Net ?

So if you wanted to check this in code , you could simply write a small peice of code as shown below.

   12         String str1 = "This is text";
   13         String str2 = str1;
   14
   15         str1 = "Text changed";
   16
   17         if (str1 == str2)
   18         {
   19             Messagebox.Show("String is value type");
   20         }
   21         else
   22         {
   23             Messagebox.Show("String is reference type");
   24
   25         }

A initial look at the code above will make you think that string is a value type.

But is it really ?
The answer is NO

String is a reference type.
The reason for the code above is that String class is immutable.


Wikipedia:

Immutable :In object-oriented and functional programming, an immutable object is an object whose state cannot be modified after it is created.

Hence when we execute str1="Text Changed" statement above , we are in essence trying to modify a immutable string. Which is not possible
What happens behind the scene is the framework creates a new string object and assigns it to str1 , since str2 is still referencing the old string that string is not destroyed.
Hence both str1 and str2 have different values.

With the introduction of .Net the categorization of value types and reference types is not as easy as it seems. Also the statement "Value types are stored on the stack and reference types are stored on the heap" is not correct. This is a topic which requires a whole post to explain. I plan to do that soon.

0 comments:

Post a Comment