Wednesday, October 12, 2016

#C# Ref Parameters vs. Out Parameters in C#


Ref Parameters vs. Out Parameters in C#


Ref: The ref keyword is used to pass an argument as a reference. This means that when value of that parameter is changed in the method, it gets reflected in the calling method. An argument that is passed using a ref keyword must be initialized in the calling method before it is passed to the called method.

Out: The out keyword is used to pass an argument as a reference. This means that when value of that parameter is changed in the method, it gets reflected in the calling method. An argument that is passed using a out keyword not to be initialized in the calling method before it is passed to the called method.

Before calling the method:
[ref]: The caller must set the value of the parameter before passing it to the called method as shown below example int I = 20;
[out]: The caller method is not required to set the value of the argument before calling the method. Most likely, you shouldn't. In fact, any current value is discarded as shown below example int K = 10;

During the call:
[ref]: The called method can read the argument at any time.
[out]: The called method must initialize the parameter before reading it.

Remote calls:
[ref]: The current value is marshaled to the remote call. Extra performance cost.
[out]: Nothing is passed to the remote call. Faster.

Example : class Program
    {
        public static void Main()
        {
            int i = 20;
            int k;
            Display(ref i);  //
            Display2(out k);
            Console.WriteLine("current ref value :" + i);
            Console.WriteLine("current out value :" + k);
            Console.ReadLine();
        }
        public static void Display(ref int i)
        {
            i = 10;
        }

        public static void Display2(out int i)
        {
            i = 10;
        }

    }
Output: Current ref value: 10
            Current out value: 10