Sunday, 2 February 2014

Working with Ref and Out Parameter in C#


Ref In c#:


Ref is basically a parameter, let we see how it can be used…
Ref Parameter: It is used as a call by reference in c#. It is used in both places when we declare a method and when we call the method . let we create the function(cube) and pass the ref parameter in it ,Now we look at the value before we call the function  and after we call the function.
class TryRef
{
    public void cube(ref int x)
    {
        x= x * x * x;  
    }
}
class Program
{
    static void Main(string[] args)
{
    TryRef tr = new TryRef();
    int y = 5;
    Console.WriteLine("The value of y before
the function call: "
+ y);
    tr.cube(ref y);
    Console.WriteLine("The value of y after the function call: " + y);
        Console.ReadLine();
    }
}

The output will be:



Now we take multiple ref parameters in our next program:

class tryref
{
    public void mul(ref int i, ref int j)
    {
        j = i * j;
    }
}
class Program
{
    static void Main(string[] args)
    {
        tryref tf = new tryref();
        int i = 5;
        int j = 10;
        Console.WriteLine("The value of i and j before the call :"+i+","+j);
            tf.mul(ref i, ref j);
            Console.WriteLine("The value of i and j after the call :" + i + "," + j);
        Console.ReadLine();
    }
}

The output will be:



 
 

Out Parameter:

Sometimes we do not want to give an initial value to the parameter , in that case we use Out Parameter. The declaration of the out parameter is same as ref Parameter but it is used to pass the value out of method.
class tryout
{
    public int mul(int a, out int b)
    {
        b = a * a;
        return b;
    }
}
class Program
{
    static void Main(string[] args)
    {
        tryout to = new tryout();
        int x,y;
        x = to.mul(10, out y);
        Console.WriteLine("The output is: "+x);
        Console.ReadLine();


    }
}


The Output will be:

 


VIDEO -