'Assigning global variables within a local function in C#
I have a program where I am assigning several variables from within a function. When I do the assignments manually it seems to work, but if I write a helper function the assignments only seem to hold within the helper function.
foo a, b
public void Setup(int v1, int v2, int v3)
{
a = new foo(v1, v2);
a.value = v3;
b = new foo(v1, v2);
b.value = v3;
}
the above code does what I want but when I try to simplify it by creating a local method to do the assignments, it doesnt seem to work
foo var a,b
public void Setup(int v1, int v2, int v3)
{
void DoThings(foo temp, int _v1, int _v2, int _v3)
{
temp = new foo(_v1, _v2);
temp.value = _v3;
}
DoThings(a, v1, v2, v3);
DoThings(b, v1, v2, v3);
}
The above compiles properly but when I try to use a or b later in my code (in another function) I get that both are null even though I know the DoThings function ran. Is there a way to do what I am trying to accomplish or should I just do all the assignments as in the first example?
Solution 1:[1]
This is a case of not understanding how parameters are passed.
Ignoring the design entirely, doing this temp = new Foo(...) just changes where temp is pointing to in memory. That's all.
It used to be the address of the passed in parameter, but now it isn't. So temp is pointing to a new address in memory that's pretty useless, because the original one is unchanged still pointing to the original address.
You can fix this by passing by reference.
Simple code change shown below. But I'd emphasize a deeper understanding of how C# passes parameters would help understand why this changes behavior.
void DoThings(ref foo temp, int _v1, int _v2, int _v3)
{
temp = new foo(_v1, _v2);
temp.value = _v3;
}
You must also pass by reference when calling:
DoThings(ref a, v1, v2, v3);
DoThings(ref b, v1, v2, v3);
This then behaves how you'd expect, and the difference is important and covered in depth in the linked documentation.
Solution 2:[2]
Does this do what you want?
foo a,b;
public void Setup(int v1, int v2, int v3)
{
void DoThings(ref foo temp, int _v1, int _v2, int _v3)
{
temp = new foo(_v1, _v2);
temp.value = _v3;
}
DoThings(ref a, v1, v2, v3);
DoThings(ref b, v1, v2, v3);
}
Why is "a" still zero in the code below?
int a = 0;
DoThings(a); // "a" will still be zero.
void DoThings(int b) // "b" is like a new variable that is set to the value of "a"
{
b = 10; // So changing "b" will not affect "a"
}
The code bellow will change the value of "a".
int a = 0;
DoThings(out a); // a = 10
void DoThings(out int b) // Putting "out" or "ref" in front of the int will make it so changing "b" will affect "a".
{
b = 10; // "a" will be the value of "b"
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Zer0 |
| Solution 2 |
