menu

Thursday, August 16, 2012

Ref and Out


What is Ref & Out?
class Program
{
    public static void Calc(int a, int b, ref int x, ref int y, ref int z)
    {
        x = a + b;
        y = a - b;
        z = a * b;
    }
    static void Main(string[] args)
    {
        int p, q, sum, sub, mul;
        p = 5;
        q = 10;
        sum = 0;      //  in case of ref we have to initialize
        sub = 0;      //  variables whose reference is passing to function
        mul = 0;      //  before passing reference to function
        Calc(p, q, ref sum, ref sub, ref mul);
        Console.WriteLine("Sum: {0}", sum);
        Console.WriteLine("Sub: {0}", sub);
        Console.WriteLine("Mul: {0}", mul);
        Console.ReadKey();
    }
}

class Program
{
    public static void Calc(int a, int b, out int x, out int y, out int z)
    {
        x = a + b;  //  we have to initialize in the
        y = a - b;  //  function
        z = a * b;  // 
    }
    static void Main(string[] args)
    {
        int p, q, sum, sub, mul;
        p = 5;
        q = 2;
        //sum = 0;      //  in case of out we don't need to initialize
        //sub = 0;      //  variables whose reference is passing to function but
        //mul = 0;      //  the calling function have to intialize that reference

        Calc(p, q, out sum, out sub, out mul);
        Console.WriteLine("Sum: {0}", sum);
        Console.WriteLine("Sub: {0}", sub);
        Console.WriteLine("Mul: {0}", mul);
        Console.ReadKey();
    }
}

No comments:

Post a Comment