I know that values sent to a function are by default passed as value and the method receives a copy of the variable. I know that when a variable is passed by reference the method can change the value of the variables from it was called. That being said, can someone help explain what’s going on in these simple illustrations? thanks in advance. Are expressions passed by reference, I guess?
using System;
class Program
{
static void Main(string[] args)
{
int x = 2;
int y = 20;
Console.WriteLine(Add(x, y));
}
static int Add(int x, int y)
{
int ans = x + y;
x = 20;
y = 40;
// return x+y;
return ans;
//returns 22
}
}
and then
using System;
class Program
{
static void Main(string[] args)
{
int x = 2;
int y = 20;
Console.WriteLine(Add(x, y));
}
static int Add(int x, int y)
{
int ans = x + y;
x = 20;
y = 40;
return x+y;
// return ans;
//returns 60
}
}
Both of these illustrate pass by value, and in general, value type semantics.
In your first example, you are saying:
This evaluates
xandyat that time and adds them together to store in ans, settingxandyto new values later does not affect the value ofans.Consider it this way:
In your second example, you are delaying the addition till after you set the new values, thus the new values of
xandyare used in the computation ofSo, in essence, you get:
I think what may be confusing you is that:
Is not a function, it’s an expression which is evaluated and returned, changing
xoryafter this statement executes does not affectansagain.The key point to remember, again, is that
ans = x + y;evaluatesxandyat the time that statement is executed. Further changes toxandydon’t come into play here.