Difference between Ref Keyword And Out Keyword

While passing Argument To Any Method Having ref and out keyword, In the following program we can see that while calling method math1 we have to initialized a variable as int b=0; and same while calling math2 it is optional to initialized a variable for passing argument.
lets 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();
        } 

Ebook Download
View all
Learn
View all