ref vs out keyword in c#

 1.Difference between ref and out keyword in C#.

Basic difference between ref and out keyword is that ref variable must be initialize before entering into the calling function, while out variable will be initialized inside into the called function.

So while ref is two-ways, out is out-only.

Ref Example:-

ref:-

   class Programm

    {

        static void Main(string[] args)

        {

            int myNum = 10, val = 10;

            ProcessNumber(ref myNum, val); 

            Console.WriteLine(myNum);

            Console.ReadLine();

        } 

        public static void ProcessNumber(ref int num, int val)

        {

            num = num + val;

        }

    }


Out Example:-

  class GFG

    {      

        static public void Main()

        {

            int i;

            Addition(out i);          

            Console.WriteLine("The addition of the value is: {0}", i);

        } 

        public static void Addition(out int i)

        {

            i = 30;

            i += i;

        }

    }

 


No comments:

Post a Comment