-1

I am boxing an integer as an object (System.Object). Then if I assign a new value to the object within the same scope, the value of the object is getting updated. But, if I try to pass the object as an argument in another function and try to assign a new value to it, the value is not getting updated. I was wondering if the object is an instance of the System.Object class and it's a reference type, then why the value of the object is not getting updated when I pass it as an argument in another function?

using UnityEngine;

public class BoxTest : MonoBehaviour
{
    void Start()
    {
        int i = 10;
        object obj = i;
        // Output : 10
        Debug.Log(obj);

        obj = 20;
        // Output : 20
        Debug.Log(obj);

        changeValueInBoxedObject(obj);

        // Output : 20, expecting 30
        Debug.Log(obj);
    }

    void changeValueInBoxedObject(object obj)
    {
        obj = 30;
    }
}
Nafiz
  • 43
  • 4
  • Do you understand why changing the variable in the method wouldn't change the variable in the calling code if you passed an `int` parameter rather than an `object`? – Pete Kirkham May 21 '22 at 09:42
  • 1
    Try this: void changeValueInBoxedObject(ref object obj). – Shane May 21 '22 at 09:45
  • Accept the argument with ref keyword in your method `changeValueInBoxedObject`, like this `changeValueInBoxedObject(ref object obj)` – DotNet Developer May 21 '22 at 09:46

1 Answers1

1

When you pass an argument into a function, it creates a new "pointer" to the value passed in. When you set obj = 30; you are re-setting the address of this new pointer to point to a new boxed version of 30.

All the while, the first "pointer" (object obj = i;) is never modified and still points to it's initial value.

You can link all of your "pointers" together with the ref keyword: void changeValueInBoxedObject(ref object obj) which should solve the issue

Note: I am using the word "pointer" to mean something that has an address either on the heap or the stack. It is not a pointer like an IntPtr

Shane
  • 875
  • 1
  • 6
  • 24