C#

Difference between ref and out parameters


The Ref and Out parameter is used when your method wants to return one or more values

Ref Keyword :

                While using the Ref keyword we need to initialize the parameter before passing to metod. If you want to pass variable as Ref parameter you need to initialize before pass. Ref keyword will pass parameter as reference, it means when the value of parameter is changed in called method it get reflected in calling method.

Example :

class Program
    {
        static void Main(string[] args)
        {
            int intRef = 2;
            int Value = MethodCall(ref intRef);
            Console.WriteLine("Ref Value : " + Value);
            Console.ReadLine();
        }

        private static int MethodCall(ref int intRef)
        {
            return 5 + intRef;
        }
    }

OUTPUT :  Ref Value : 7

Out Keyword :

Wjile using Out keyword we don’t need toinitialize the parameter before passing to method. Out keywork also you pass as paameter as reference but here we need to initialize out parameter before it return to calling method.

Example :

static void Main(string[] args)
        {
            int intOut;
            int Value = MethodCall(out intOut);
            Console.WriteLine("Out Value : " + Value);
            Console.ReadLine();
        }

        private static int MethodCall(out int intOut)
        {
            return intOut = 3;
        }

OUTPUT :  Out  Value : 3

Note :
1)      Passing by reference and the concept of reference type these two concepts are not the same.
2)      Properties cannot be passed to ref or out parameters since internally they are functions.