I’ve been struggling to understand what’s going on with a method I’ve got to understand for my test, I’m having a hard time figuring out the reason I’m getting the results I get, any explanation on how the “f” method works it’s greatly appreciated
class Program {
static void Main(string[] args)
{
A b = new A(); b.y = b.x;
b.f(b.y); b.g();
Console.WriteLine(b.x[0] + " " + b.x[1]); // Prints 1 7
Console.WriteLine(b.y[0] + " " + (b.x[1] + b.y[1])); // 1 14
}
}
public class A {
public int[] x = {1, 2};
public int[] y;
public void f(int[] z)
{
z[1] += 5;
}
public void g()
{
A a = new A ();
a.x[0]++;
a.x[1]--;
}
}
Let me explain what I did understand, b.y gets created as an array and it gets the values in b.x, now, when we call b.f, we pass that method b.y which is [1, 2], now, and here’s where I get stuck, z seems to be the b.y array, so it has [1, 2] as value, when the method adds 5 to the element in the position 1 (which is 2) I get [1, 7] as result of that, when the method ends and my program goes back to the main, somehow, b.y AND b.x BOTH are now [1, 7], how did that happen?, I thought the method was only modifying b.y since that’s the one that got passed. Also, the g function doesn’t add anything as the “a” value is a local variable that “dies” as the method ends, right?. I hope someone can help me, I’ve got to pass this test!. Thanks ;]
Here we go:
bis initialized with a type ofA.bis created, it sets the value ofb.xto{1, 2}.b.yis then assigned tob.x, however, because they are arrays, they are now referencing the same data.b.fis called, and hasb.ypassed to it (remembering, thatb.yandb.xare referencing the same data right now). Essentially, z also points to the same data during theffunction.b.fadds 5 to the value at index 1 of the shared data, which is 2. So 2 + 5 = 7.Console.WriteLineprintsb.x[0]which is still 1. Then it printsb.x[1]which is now 7 (as above).Console.WriteLineprintsb.y[0], which is still 1 (because they share the same data). Then it printsb.x[1]+b.y[1]. They both share the same data.. and the data at index 1 is 7. 7 + 7 = 14.You are correct about the
gmethod in that the variable is local and doesn’t do anything.Hope that helps.