Jess Jess - 6 days ago 6
C# Question

Can someone please explain the logic of this C# code that involves the 'passing by output' concept?

static int Test(out int x, int y=4)
{
x = 6;
return x * y;
}

static void Main(string[] args)
{
int a;
int z = Test(out a);
Console.WriteLine(a + z);
}


The output is 30, but I do not understand exactly how.

I get that in the Test() method, the parameter x outputs the value of 6 into the Main() method, but how, if you are just outputting the 6 does it send the return value of 24?

I don’t know if that all made sense. I am struggling with this whole “pass by output” concept, I guess.

Please try to explain this concept in the simplest Barney-style way possible. If it’s overly technical and complicated, it will likely just confuse me more.

Answer

Comments below:

static void Main(string[] args) 
{
    int a;
    int z = Test(out a); // returns z as 6 * 4 = 26 and sets a = 4;
    Console.WriteLine(a + z); // 26 + 4 = 30
}

out allows developer to pass and update a parameter value by reference, so that it is reflected in the caller method (same as a in your case)

From C# Specifications:

A parameter declared with an out modifier is an output parameter. An output parameter does not create a new storage location. Instead, an output parameter represents the same storage location as the variable given as the argument in the function member or delegate invocation. Thus, the value of an output parameter is always the same as the underlying variable.

The difference between ref and out is that:

• Every output parameter of a function member or anonymous function must be definitely assigned before the function member or anonymous function returns normally.

Comments