2

I am trying to update the variable ref container that was passed via constructor to set to equal to a new object in a Run method. Of course, in Run method I am updating the reference of to Foo::_container not the variable container that was defined in Main. So I am wondering if there is a way to save the container reference that was passed via constructor and subsequently update the value of reference. Thank you.

public class Foo
{
    private IContainer _container;

    public Foo(ref IContainer container)
    {
        _container = container;
    }

    public void Run()
    {
        var temp = new Container();
        _container = temp;
    }
}


static class Main
{
    static void Main()
    {
        IContainer container = null;
        (new Foo(ref container)).Run();

        // container is still null
        Console.WriteLine(container);
    }
}
Aryan Firouzian
  • 1,940
  • 5
  • 27
  • 41
Node.JS
  • 1,042
  • 6
  • 44
  • 114
  • I don't believe you can do what you are trying to do. The ref argument is local to the method. Taking a step back, what exactly are you trying to achieve? You aren't keeping `Foo` alive so what is the purpose of attempting to store the `IContainer` reference or having a separate `Run()` method? – Nigel Whatling May 01 '18 at 00:34
  • 1
    Since you can't have a ref field, the discussion of [why and work arounds in this question](https://stackoverflow.com/questions/2980463/how-do-i-assign-by-reference-to-a-class-field-in-c) is very relevant. – Mike Zboray May 01 '18 at 01:11

0 Answers0