Ref Versus Out keyword

Ref and Out keywords are  use for same purpose but there are difference is ref variable cannot use without initialization but out variable use without initialization.

(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 keywordref keywordNumber before Method call:13

Number in Method : 25

Number after Method call:25

(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:

Number in Method call :25

Number after Method Call:25

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.