Search code examples
c#boxing

After boxing, cannot change the object value by passing the object as an argument of a function


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;
    }
}


Solution

  • 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