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;
}
}
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:
Then:
You may find Eric Lippert’s recent blog post on "ref returns and ref locals" interesting.