Working With Ref and Out Parameter in C#

Here we discuss the ref and out parameters in C#. They are basically parameters and we can use it in a different way.

ref parameter: It is used as a call by reference in C#. It is used both places; when we declare a method and when we call the method. The following example will explain how we use the ref parameter in C#. In this example we create a function (cube) and pass a 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:

RefOut1.jpg

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:

RefOut2.jpg

Out parameter: Sometimes we do not want to give an initial value to the parameter; in this case we use the out parameter. The declaration of the out parameter is the same as the ref parameter. But it is used to pass the value out of a method. Now we look at the example:

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:

RefOut3.jpg
 

Up Next
    Ebook Download
    View all
    Learn
    View all