C# Tutorial : The ref and out Parameters

Leave a Comment
Did you ever need your method to return more than one value? You may need to do this occasionally, or you may need to use the same variables that you pass as an argument of the method. When you pass a reference type, such as a class instance, you don’t have to worry about getting a value in a separate variable because the type is already being passed as a reference and will maintain the changes when it returns. A problem occurs when you want the value to be returned in the value  type. The ref and out parameters help to do this with value types.

The out keyword defines an out type parameter. You Use the  out  keyword to pass a parameter to a method. This example is passing an integer type variable as an out parameter. You define a function with the out keyword as an argument with the variable type:
 myMethod(out int iVal1)

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.
using System;
public class myClass
{
  public static void ReturnData(out int iVal1, out int iVal2)
     {
       iVal1 = 2;
       iVal2 = 5;
     }
  public static void Main()
  {
    int iV1, iV2; // variable need not be initialized
    ReturnData(out iV1, out iV2);
    Console.WriteLine(iV1);
    Console.WriteLine(iV2);
  }
}

The  ref keyword defines a  ref type parameter. You pass a parameter to a method with this keyword, as  in listing 31. This example passes an integer type variable as a  ref parameter. This is a method definition:
myMethod(ref int iVal1)

You can use the ref parameter as a method input parameter and an output parameter. Any changes made to the parameter will be reflected in the variable.
using System;
public class myClass
{
public  static  void  ReturnData(ref  int  iVal1,  ref  int  iVal2,  ref
int iVal3)
{
iVal1 +=2;
iVal2 = iVal2*iVal2;
iVal3 = iVal2 + iVal1;
}
public static void Main()
{
int iV1, iV2, iV3; // variable need not be initialized
iV1 = 3;
iV2 = 10;
iV3 = 1;
ReturnData(ref iV1, ref iV2, ref iV3);
Console.WriteLine(iV1);
Console.WriteLine(iV2);
Console.WriteLine(iV3);
}

In this method,  ReturnData  takes three values as input parameters, operates on the passed data returns the result in the same variable.

0 comments:

Post a Comment