C# Language Function with multiple return values Ref and Out Parameters


Example

The ref keyword is used to pass an Argument as Reference. out will do the same as ref but it does not require an assigned value by the caller prior to calling the function.

Ref Parameter :-If you want to pass a variable as ref parameter then you need to initialize it before you pass it as ref parameter to method.

Out Parameter :- If you want to pass a variable as out parameter you don’t need to initialize it before you pass it as out parameter to method.

static void Main(string[] args)
{
    int a = 2;
    int b = 3;
    int add = 0;
    int mult= 0;
    AddOrMult(a, b, ref add, ref mult); //AddOrMult(a, b, out add, out mult);
    Console.WriteLine(add); //5
    Console.WriteLine(mult); //6
}

private static void AddOrMult(int a, int b, ref int add, ref int mult) //AddOrMult(int a, int b, out int add, out int mult)
{
    add = a + b;
    mult = a * b;
}