Tuesday, 11 October 2011

Difference Between Ref and Out In C#

The out and the ref parameters are used to return values in the same variables, that you pass as an argument of a method. These both parameters are very useful when your method needs to return more than one values.

  • ref = Reference, when parsed to a method, the method references that original variable and doesn't create another instance. So if you make a change to a var parsed into that method when ref is used, it will affect the calling method

  • out = Out is a little different in that you can return more than one value from a method (apart from a return )


Difference?

- A variable to be sent as ref parameter must be initialized.
It is intended to be changed in the method to which it is passed.

- A variable to be sent as out parameter don't need to be initialized
before being passed to a method, because it must be assigned in that method.
It is not intended to be changed, but intended to be assigned(or reassigned)
in the method to which it is passed.

- A "ref" parameters need initialization BEFORE you call the function; "out"
does not.

The following will not compile:
string a;
f(ref a);

The following will compile:
string a;
g(out a);

Decription:
The out Parameter:
The out parameter can be used to return the values in the same variable passed as a parameter of the method. Any changes made to the parameter will be reflected in the variable.

public class mathClass

{

public static int TestOut(out int iVal1, out int iVal2)

{

iVal1 = 10;

iVal2 = 20;

return 0;

}

public static void Main()

{

int i, j; // variable need not be initialized

Console.WriteLine(TestOut(out i, out j));

Console.WriteLine(i);

Console.WriteLine(j);

}

}

The ref parameter:
The ref keyword on a method parameter causes a method to refer to the same variable that was passed as an input parameter for the same method. If you do any changes to the variable, they will be reflected in the variable.
You can even use ref for more than one method parameters.


public class myClass

{

public static void RefTest(ref int iVal1 )

{

iVal1 += 2;

}

public static void Main()

{

int i; // variable need to be initialized

i = 3;

RefTest(ref i );

Console.WriteLine(i);
}
}

Thanks Happy Coding :)


References
  1. http://www.dotnetobject.com/showthread.php?tid=171
  2. http://www.c-sharpcorner.com/UploadFile/mahesh/out_and_ref11112005002102AM/out_and_ref.aspx

1 comment: