Whats the difference between ref parameter and return value (methods)

I've been studying methods and i have stumbled across the "ref" method. However both codes seem to accomplish the same thing:

class Program
{
    static void Main(string[] args)
    {
        int number;

        number = 5; 
        Console.WriteLine("Before method number= {0}", number);

        AddThree (ref number);

        Console.WriteLine("After method number={0}", number);
        Console.ReadLine();

    }

    private static void AddThree(ref int  lol) //carbon copy....so  int number= 5  here
    {
        lol  = 3; 
        Console.WriteLine("inside method number={0}", lol);


    }


}
}

class Program
{

    static void Main(string[] args)
    {

       int number;
       int print; 


        number = 5;
        Console.WriteLine("Before method number= {0}", number);

        print =AddThree(number);

        Console.WriteLine("After method number={0}", print);
        Console.ReadLine();

    }

    private static int AddThree(int lol) //carbon copy....so  int number= 5  here
    {
        lol  = 3; 
        Console.WriteLine("inside method number={0}", lol);
        return lol;


    }


}

}

--

Is there an advantage that ref parameter has over return value? personally i dont see a massive difference..

Jon Skeet
people
quotationmark

Is there an advantage that ref parameter has over return value? personally i don't see a massive difference.

Well typically, ref is used when there's already something else being returned - e.g. for int.TryParse (which uses out, but that's similar). C# only supports returning a single value, so if you want two outputs from a method you have options of:

  • out parameters
  • ref parameters
  • Returning a composite value (likely to be more common in C# 7 with ValueTuple)

But there are other differences - importantly, changes to the ref parameter are visible immediately in terms of changing the original variable. That's most simply demonstrated when you have two ref parameters aliasing the same variable:

using System;

class Test
{
    static void Main()
    {
        int x = 0;
        RefTwo(ref x, ref x);
    }

    static void RefTwo(ref int a, ref int b)
    {
        Console.WriteLine(a); // 0
        b = 5;
        Console.WriteLine(a); // 5!
    }
}

Oh, and as a little oddity, if you want a partial method to "return" a value, you basically need a ref parameter as partial methods must be void.

I would generally avoid ref parameters unless there's a very clear benefit. They make the interaction more complicated, in my view.

people

See more on this question at Stackoverflow