You seem to have misunderstood how variable scopes work. The x
in Assign
is not the same as x
in Main
. This is because in C#, int
is passed by value (this is the same as C++, BTW).
You probably meant to mark the variables in Assign
as ref
:
class Program
{
static void Assign(ref int x, ref int z)
{
x = 3;
z = 2;
}
static void Sum(int x, int z)
{
Console.WriteLine(x + z);
}
static void Main(string[] args)
{
int x = 0, z = 0;
Assign(x, z);
Sum(x, z);
}
}
Note the this is not recommended, because now Assign
has side-effects. This is better:
class Program
{
static void PrintSum(int x, int z)
{
Console.WriteLine(x + z);
}
static void Main(string[] args)
{
PrintSum(3, 2);
}
}
For more background, I would suggest looking at the difference between pass-by-reference and pass-by-value.
3
solved How to assign a variable in one method and change/use it in another method? [closed]