Difference between ref and value

Difference between passing reference types by ref and by value

A Brief Insight into Reference Types:
Data for Reference types is stored on the heap and a pointer (which points to the data on the heap) is created on the stack, whenever an instance of reference type is created the pointer is returned back and is used to manipulate the data on the stack. Hence Hashtable hst = new HashTable(); actually returns back the pointer. Now when this pointer is passed by val, all we are doing is duplicating the pointer but it still points to the same memory on the heap and hence any manipulation done to the object in the called method will manipulate the same data to which original hashtable pointer was pointing. In case of passing by ref, the original pointer itself is passed to the called function. 

So what is the difference between passing byref v/s passing byval? Lets take a look at the slightly modified version of above code:
static void Main()
{
Hashtable hst = new Hashtable(3);
hst.Add(1,1);
PassHashTableByVal(hst); //by default .net parameters are passed by val
Console.WriteLine("Count after passing byval: {0}",hst.Count); //will print 2
PassHashTableByRef(ref hst);
Console.WriteLine(揅ount after passing byref: {0}? hst.Count); //will throw a null reference exception.
Console.Read();
}

static void PassHashTableByVal(Hashtable h1)
{
h1.Add(2,2);
h1 = null;
}

static void PassHashTableByRef(ref Hashtable h2)
{
h2.Add(3,3);
h2 = null;
}

posted on 2006-03-02 21:49  无心三立  阅读(163)  评论(0编辑  收藏  举报

导航