Reference types are always passed by reference so what’s the difference between passing a reference type by value or by ref keyword. Let’s try to understand by some code samples:
Let’s say we have a class MyClass defined below, Class in .Net is a reference type as you should know.
class Reftype { public int i; }
Let’s now consider below code where we are passing the class object normally i.e. by value as well by ref keyword:
public void RefTypePassNormal(Reftype refType) { refType.i =20; } public void RefTypePassByRef(ref Reftype refType) { refType.i =30; }
Here is the calling code
style="display:block; text-align:center;"
data-ad-format="fluid"
data-ad-layout="in-article"
data-ad-client="ca-pub-5021110436373536"
data-ad-slot="9215486331">
Reftype refType = new Reftype(); refType.i=10; RefTypePassNormal(refType); Console.WriteLine(refType.i);//Prints 20 RefTypePassByRef(ref refType); Console.WriteLine(refType.i);//Prints 30
So as you can see right now no difference
Let’s Change the methods now as below to know the difference:
public void RefTypePassNormal(Reftype refType) { refType.i =20; refType =null; } public void RefTypePassByRef(ref Reftype refType) { refType.i =30; refType =null; }
Again let’s see the calling code
style="display:block; text-align:center;"
data-ad-format="fluid"
data-ad-layout="in-article"
data-ad-client="ca-pub-5021110436373536"
data-ad-slot="9215486331">
Reftype refType = new Reftype(); refType.i=10; RefTypePassNormal(refType); Console.WriteLine(refType.i);//This still Prints 20 RefTypePassByRef(ref refType); Console.WriteLine(refType.i);//Null Reference Exception here