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;
}
}
In case you want to pass parameters to the constructor, you include the parameters between the parentheses after the class name, like this: MyClass myClassVar = new MyClass(1975); This example passes one parameter to the MyClass constructor that takes an int as parameter.
Pass by Value: The method parameter values are copied to another variable and then the copied object is passed, that's why it's called pass by value. Pass by Reference: An alias or reference to the actual parameter is passed to the method, that's why it's called pass by reference.
"Passing by value" means that you pass the actual value of the variable into the function. So, in your example, it would pass the value 9. "Passing by reference" means that you pass the variable itself into the function (not just the value). So, in your example, it would pass an integer object with the value of 9.
Call By Value: In this parameter passing method, values of actual parameters are copied to function's formal parameters and the two types of parameters are stored in different memory locations.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With