Both output the same result.
That's because as well as changing whether or not it's a ref
parameter, you've changed where you've got the output.
Here's a version of your first piece of code that is closer to the second, so they only differ in whether or not it's a ref parameter:
public static void Sqr(int x)
{
x = x * x;
}
static void Main(string[] args)
{
int a = 3;
Sqr(a);
Console.WriteLine(a);
}
Now the output will be 3, because the value of a
hasn't changed - its value was passed to the Sqr
method. In your second example, the variable itself is passed by reference, so x
in the Sqr
method and a
in the Main
method refer to the same storage location... the change to the value of x
can be "seen" via a
after the method has returned.
When is the second, passing an argument by reference better?
When you want changes in the parameter to be reflected in the argument. That's relatively rare, and I'd encourage you to use value parameters by default. For example, it would be more idiomatic to write Sqr
as:
public static int Sqr(int x)
{
return x * x;
}
Then call it as:
a = Sqr(a);
ref
parameters are relatively rarely useful in my experience - but it's important to understand how they work. (You may find my article on parameter passing useful for more details.)