What is ref and out parameter in C#?

Answer: Both ref and out parameter or keywords in C# are used to pass an argument as a reference to a method in C# program. For example,

public void X(ref int val)
public void Y(out int val)

The difference between ref and out parameters in C# is
The ref variable must be initialized before passing to a function. Whereas, there is no need to initialize out variable before passing it to function.However, if we initialize out variable before passing to method, there is no harm, but, it is useless, as we must initialize or assigned a value to out variable within the function body.

Example with comments:

class A
{
    public void X(ref int val)
    {
        //we can read the value or write the value.
        Console.WriteLine("Read/write value:" + val);
        val = 20;
    }
    public void Y(out int val)
    {
        // can not read val, so useless to initialize out 
        //parameter before passing.
        //On read here compiler will flash an error.
        val = 10;// withing this function a must be assigned a value.
        Console.WriteLine("Value assigned:"+val);//read ok.
    }
}
namespace refandout
{
    class Program
    {
        static void Main(string[] args)
        {
            //Test ref
            A a = new A();
          
            int x =5;           
            a.X(ref x);
            Console.WriteLine("Value of x:" + x);

            //Test out
            int y;
            a.Y(out y);
            Console.WriteLine("Value of y:" + y);

        }
    }
}

Points:

  • Since, ref and out variables in C# are passed as a reference to a function, the value changed in function body will be reflected in calling function.
  • Also, ref is IN/OUT (Read/Write) parameter as we initialize it before passing to function, we can use the value or modify the value inside the function body.
  • And out is OUT (Write) parameter, means, only we can assign/write the value to it and cannot read the value before assignment if we have initiated before passing.

Related Posts