ref and out parameters in C#

 

Whenever you want to pass the parameter as reference instead of just variable you can use ref and out parameters in C#. Today we discuss about ref and out parameters and difference between both.

 

ref parameter:

Ref parameters are initially assigned by caller and called method can change its value, that means it is optional. If caller method not assigning any value to ref parameter it produces compile-time error and it doesn't care even though called method won't assign any value to it. If called method not changing the value of ref parameter, its value is going to initial value assigned by caller method.

 

For example consider below example where we have GetEmployeeInfo() method which takes one normal int variable and another ref int variable.

 

class Program

{

        static void Main(string[] args)

        {

            int iSal = 0;

            GetEmployeeInfo(1, ref iSal);

        }

 

        private static void GetEmployeeInfo(int id, ref int sal)

        {

            sal = sal + 1000;

        }

}

 

While calling the GetEmployeeInfo() method if you are not assigning value for iSal variable, you will get compile-time error. Changing ref variable in Called method optional, that means changing the ref value like sal = sal + 1000; is optional. As in the above example if you change the ref value in called method, the value is going to be 1000 else 0.

 

out parameter:

The out parameter is also same as ref parameter, but called method as to assign the value for out parameter. Assigning the out parameter value while is optional. If the called method not assigning the value for out parameter, it produces the compile-time error.

 

For example take same example GetEmployeeInfo() method, now change ref parameter to out parameter as shown below.

 

class Program

{

        static void Main(string[] args)

        {

            int iSal;

            GetEmployeeInfo(1, out iSal);

        }

 

        private static void GetEmployeeInfo(int id, out int sal)

        {

            sal = 1000;

        }

}

 

This time we didn't assign the value for iSal variable in the caller method, still it is not producing any compile-time error. But if you didn't change the value in called method, that means if you are not assigning the value for variable sal in GetEmployeeInfo() method it produces compile-time error.

 

Differences between ref and out parameters

Both ref and out parameters are reference based only, only difference is ref parameter requires initial value whereas out parameter not requires(it is optional).  But in the called method, out variable requires data assignment whereas ref parameter not requires(it is optional).