-8

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);
    }
}
Rink prog
  • 3
  • 2

1 Answers1

2

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.

sdgfsdh
  • 33,689
  • 26
  • 132
  • 245
  • 1
    +1 but I don't think the OP "probably" meant to use ref at all, they are just a confused beginner; your second example is the only one that makes sense. – Polyfun Sep 21 '17 at 16:25
  • To me, this question looks like homework about reference-vs-value, so I answered it that way. – sdgfsdh Sep 21 '17 at 16:26
  • Another option is top use tuple deconstruction in c# 7.0: `static (int, int) Assign() { return (3, 2); }` Then in the calling code: `(int x, int y) = Assign();` – Chris Dunaway Sep 21 '17 at 17:52