Ref Versus Out keyword

(A) Ref Keyword

  1. When a parameter pass with ref keyword in function then function work with same variable value that is passed in function call. If variable value change then function parameter value also change.
  2. Both the function definition and function calling must explicitly use the ref keyword.
  3. In function call argument passed to a ref parameter must first be initialized.
  4. ref parameter variable should not be declare as a constant variable.
  5. It is not compulsory that ref parameter name should be same in both function definition and function call.

Illustration with an Example

using System;
    class Program
    {
        static void Add(ref int val)
        {
            val += 12;
            Console.WriteLine("Number in Method : {0}", val);
        }
        static void Main(string[] args)
        {
            int number = 13;
            Console.WriteLine("Number before Method call:{0}",number);
            Add(ref number);
            Console.WriteLine("Number after Method call:{0}",number);
            Console.Read();
        }
    }

Output:
Ref keyword output

(B) Out Keyword

  1. When a parameter pass with out keyword in function then function work with same variable value that is passed in function call. If variable value change then function parameter value also change.
  2. Both the function definition and function calling must explicitly use the out keyword.
  3. It is not necessary to initialize out parameter variable that is pass in function call.
  4. out parameter variable should not be declare as a constant variable.
  5. It is not compulsory that out parameter name should be same in both function definition and function call.

Illustration with an Example

using System;
    class Program
    {
        static void Add(out int val)
        {
            val = 12;
            val += 13;
            Console.WriteLine("Number in Method call:{0}",val);
        }
        static void Main(string[] args)
        {
            int number;
            Add(out number);
            Console.WriteLine("Number after Method Call:{0}",number);
            Console.Read();
        }
    }

Output:
out keyword

Although the ref and out keywords cause different run-time behaviour, they are not considered part of the method signature at compile time. Therefore, methods cannot be overloaded if the only difference is that one method takes a ref argument and the other takes an out argument.