Friday, 19 May 2017

ref vs out parameter in c#

ref tells the compiler that the object is initialized
before entering the function,while out tells
the compiler that the object will be initialized
inside the function.

ex: ref:
=========

public static void Main()
{
 int i = 3; // Variable need to be initialized
 sampleMethod(ref i );
}

public static void sampleMethod(ref int sampleData)
{
 sampleData++;
}

Note :
1.A ref variable needs to be initalized before
passing it in.
2.ref parameters can be thought of as both
input and outup variables.


ex: out :
===========

public static void Main()
{
 int i, j; // Variable need not be initialized
 sampleMethod(out i, out j);
}
public static int sampleMethod(out int sampleData1, out int sampleData2)
{
 sampleData1 = 10;
 sampleData2 = 20;
 return 0;