Difference between Ref and Out keywords

 Difference between Ref and Out keywords


Ref 

It is necessary the parameters should initialize before it pass to ref.

It is not necessary to initialize the value of a parameter before returning to the calling method.

When we use ref, data can be passed bi-directionally.




Out 

The out is a keyword in C# which is used for the passing the arguments to methods as a reference type.

It is generally used when a method returns multiple values.

When we use OUT data is passed only in a unidirectional way (from the called method to the caller method).

It is not necessary to initialize parameters before it pass to out.



Example

public class Test {  

    // Main method

    static public void Main()

    {  

        // Declaring variable

        // without assigning value

        int G=10;  

        // Pass variable G to the method

        // using out keyword

        Sum(ref G);

  

        // Display the value G

        Console.WriteLine("The sum of" + " the value is: {0}", G);

    }  

    // Method in which out parameter is passed

    // and this method returns the value of

    // the passed parameter

    public static void Sum(ref int G)

    {

        G += G;

    }

}


output : 20, but we have to assign the variable before used otherwise we will get an error.


Example for out parameter :


public class Test 

{    // Main method

    static public void Main()

    {

          // Declaring variable

        // without assigning value

            int G;  

        // Pass variable G to the method

        // using out keyword

        Sum(out G);  

        // Display the value G

        Console.WriteLine("The sum of" +  " the value is: {0}", G);

    }  

    // Method in which out parameter is passed

    // and this method returns the value of

    // the passed parameter

    public static void Sum(out int G)

    {

        G = 80;

        G += G;

    }

}


The output is : 160


Summary:


1. Both are treated differently @ runtime but same in the compile time, so can’t be overloaded.

2. Both are passed by references except ‘ref’ requires that the variable to be initialized before passed.