Rink prog Rink prog - 1 month ago 8
C# Question

How to assign a variable in one method and change/use it in another method?

What changes do I have to make for the x and z variables to retain the values they are assigned in the Assign method? I have only recently started learning C# for college after learning C++ for 2 years in school so this is very confusing to me.

class Program
{
static void Assign(int x, 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);
}
}

Answer Source

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.