…Whenever an instance of reference type is created the pointer is returned back… 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.
Shared Sub Main()
Dim hst As Hashtable = New Hashtable(3)
hst.Add(1, 1)
‘by default.net parameters are passed by val
PassHashTableByVal(hst)
‘will print 2
Console.WriteLine("Count after passing byval: {0}", hst.Count)
PassHashTableByRef(hst)
‘will throw a null reference exception.
Console.WriteLine("Count after passing byref: {0}", hst.Count)
Console.Read()
End Sub
Shared Sub PassHashTableByVal(ByVal h1 As Hashtable)
h1.Add(2, 2)
h1 = Nothing
End Sub
Shared Sub PassHashTableByRef(ByRef h2 As Hashtable)
h2.Add(3, 3)
h2 = Nothing
End Sub
A null reference exception in case of passing hashtable as by ref is thrown because in the PassHashTableByRef() we are setting h2 to null which actually is same as hst, whereas in case of passing it by val we are only setting the copy of the hst pointer to null.
1Difference between passing reference types by ref and by value
By Sachin Nigam November 07, 2005
Parameter passing in C#
Honorable Mention