Pass value by reference in constructor, save it, then change later, how?

How to implement this functionality? I think it does not work because I save it in the constructor? Do I need to make 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; } } 
+7
source share
2 answers

You cannot, in principle. Not directly. Aliasing "pass by reference" is valid only in the method itself.

The closest you could get is a modified shell:

 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 can find Eric Lippert's latest blog post on "ref returns and ref locals" .

+12
source

You can come close, but in fact, John is simply responding in disguise:

  Sub Main() Dim currentInt = 1 'Should be 1 Console.WriteLine(currentInt) 'is 1 Dim tc = New Action(Sub()currentInt+=1) 'should be 1 Console.WriteLine(currentInt) 'is 1 tc.Invoke() 'should be 2 Console.WriteLine(currentInt) 'is 2 :) End Sub 
0
source

All Articles