Sunday, December 12, 2010

Value Type and Reference Type in C#.

As an answer to one of the questions (stated below) in StackOverFlow I have stated some details over behavior of ValueType and Reference Type. Sharing it here.


QUESTION:


using System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;

namespace
ConsoleApplication13
{
public class Student
{
public int Marks { get; set; }
public Student(int marks)
{
this.Marks = marks;

}
public void AssignMarks(Student st)
{
st
= null;
}
public void AssignMarks(ref Student st)
{
st
= null;
}
}
class Program
{
static void Main(string[] args)
{
Student st = new Student(50);
st
.AssignMarks(st);
Console.WriteLine(st.Marks);
Student st1 = new Student(50);
st
.AssignMarks(ref st1); // NullReferenceException
Console.WriteLine(st1.Marks);
}
}
}


ANSWER:

Here, Student is a reference type, so your object is stored in Heap. The pointer to this object lies in Stack (since it is a variable).

"Method - 1"

When you pass the object in first method (without ref), you are sending the pointer which points to some address in Heap (again, since Student is of reference type). This pointer is "copied" to the argument and is local to the method only. Now the method can access to that memory location and "change" the value stored in that address.

As Below,

public void AssignMarks(Student st)
{
st
.Marks=100;
}

In this case, WriteLine in Program.Main method will pring 100 !!!

Coming back to your first method. The pointer is "copied" in the argument of your method. By doing,'st = null', this local copy points to "new" memory location in Heap, and the original memory location remains as it is. Thus, when the call returns back. Your object remains same.

"Method - 2"

On the other hand, when you pass this argument as 'ref', it is actually sending pointer to your original variable (behavior remains same for ValyeType and ReferenceType). In this case, the method has access to the memory location of the variable itself (not to the value it is pointing to). So, if the method changes anything in this argument, it is reflected as-is in the calling method. Has to be, right? In all sense it is the same memory location being accessed from different places and different variables.

Since you have explicitly assigned 'null' to your object. It is throwing Null Reference exception.