1

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?

3
  • IMHO returning a foo is a better solution foo DoThings(...){...} a = DoThings(...); ... Commented Apr 29, 2022 at 4:50
  • "The above compiles properly" - No, it doesn't. Commented Apr 29, 2022 at 6:03
  • 2
    There are no global variables in your code. In fact, C# does not have global variables. Commented Apr 29, 2022 at 6:06

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.