Difference between Ref Keyword And Out Keyword

While passing an argument to any method having a ref or out keyword, as we can see in the following program, that while calling method math1 we have to initialize a variable as "int b=0;" and in the same manner while calling math2 it is optional to initialize a variable for passing an argument. Let's see a small program.
 

 namespace
OOPSProject
 {
     class Program
 
    {
         //No Input & Output
 
        void Test1()
         {
             Console.WriteLine("First method");
         }
         //No Output has Input
 
        void Test2(int x)
         {
             Console.WriteLine("Second method: " + x);
         }
         //No Input has Output
 
        string Test3()
         {
             return "Third method";
         }
         //Has Input & Output
 
        string Test4(string name)
         {
             return "Hello " + name;
         }
         //Returning multiple values:
 
        int Math1(int x, int y, ref int z)
         {
             z = x * y;           
             return x + y;
         }
         int Math2(int x, int y, out int z)
         {
             z = x * y;
             return x + y;
         }
         static void Main(string[] args)
         {
             Program p = new Program();           
             p.Test1(); p.Test2(100);
             Console.WriteLine(p.Test3());
             Console.WriteLine(p.Test4("Raju"));
             int b = 0;  //Initialization is mandatory
 
            int a = p.Math1(100, 50, ref b);
             Console.WriteLine(a + "   " + b);
             int n;  //Initialization is optional
 
            int m = p.Math2(100, 50, out n);
             Console.WriteLine(m + "   " + n);
             Console.ReadLine();
 
      }
     }
 }


Similar Articles