Search code examples
c#parametersreferenceint

pass value by reference in constructor, save it, then modify it later, how to?


How do I implement this functionality? I think its not working because I save it in the constructor? Do I need to do some Box/Unbox jiberish?

    static void Main(string[] args)
    {
        int currentInt = 1;

        //Should be 1
        Console.WriteLine(currentInt);
        //is 1

        TestClass tc = new TestClass(ref currentInt);

        //should be 1
        Console.WriteLine(currentInt);
        //is 1

        tc.modInt();

        //should be 2
        Console.WriteLine(currentInt);
        //is 1  :(
    }

    public class TestClass
    {
        public int testInt;

        public TestClass(ref int testInt)
        {
            this.testInt = testInt;
        }

        public void modInt()
        {
            testInt = 2;
        }

    }

Solution

  • You can't, basically. Not directly. The "pass by reference" aliasing is only valid within the method itself.

    The closest you could come is have a mutable wrapper:

    public class Wrapper<T>
    {
        public T Value { get; set; }
    
        public Wrapper(T value)
        {
            Value = value;
        }
    }
    

    Then:

    Wrapper<int> wrapper = new Wrapper<int>(1);
    ...
    TestClass tc = new TestClass(wrapper);
    
    Console.WriteLine(wrapper.Value); // 1
    tc.ModifyWrapper();
    Console.WriteLine(wrapper.Value); // 2
    
    ...
    
    class TestClass
    {
        private readonly Wrapper<int> wrapper;
    
        public TestClass(Wrapper<int> wrapper)
        {
            this.wrapper = wrapper;
        }
    
        public void ModifyWrapper()
        {
            wrapper.Value = 2;
        }
    }
    

    You may find Eric Lippert's recent blog post on "ref returns and ref locals" interesting.