Saturday, August 11, 2018

Difference between REF and OUT

 1. What is Difference between REF and OUT in C#.

 The Ref and out keywords are used to pass argument within a method and function.
 Both Indicate that Argument/parameter passed by Reference.


 * By Default parameter passed by method to a value.


Ref :  ref tells the compiler that the object is initialized before entering the function.

So Ref is Two way while Out is only one way.

Example:

 class Program
    {
        static void Main(string[] args)
        {
            int i = 0;
            SampleA.TestRef(ref i);
            Console.ReadKey();
        }
    }


    //Sample Method------


    public static class SampleA

    {

        public static int TestRef(ref int id)

        {
            id = id + 1;
            Console.WriteLine("REF "  + id);
            return id;
        }

    }


OUT:

The out keyword is also used to pass an argument like ref keyword, but the argument can be passed without assigning any value to it.

Example:

\class Program
    {
        static void Main(string[] args)
        {
            int i;//Used Unassigned variable
            SampleA.TestRef(out i);
            Console.ReadKey();
        }
    }


    //Sample Method------

    public static class SampleA
    {

        public static int TestRef(out int id)
        {
            id = 5;// need to initialzed inside the block
            id = id + 1;
            Console.WriteLine("REF "  + id);
            return id;
        }
    }


Passing a parameter value by Ref is useful when the called method is also needed to modify the pass parameter.Declaring a parameter to an out method is useful when multiple values need to be returned from a function or method.

  1. public static string GetNextNameByOut(out int id)  
  2. {  
  3.     id = 1;  
  4.     string returnText = "Next-" + id.ToString();  
  5.     return returnText;   



Ref / Out keyword and method Overloading

Both ref and out are treated differently at run time and they are treated the same at compile time,
so methods cannot be overloaded if one method takes an argument as ref and the other takes an argument as an out.





No comments:

Post a Comment