We know that int is a value type and so the following makes sense:
int x = 3;
int y = x;
y = 5;
Console.WriteLine(x); //says 3.
Now, here is a bit of code where we want to for lack of a better term “link” the two variables point to the same memory location.
int x = 3;
var y = MagicUtilClass.linkVariable(() => x);
y.Value = 5;
Console.WriteLine(x) //says 5.
The question is: How does the method linkVariable look like? What would it’s return type look like?
Although, I titled the post as making a value type behave as a reference type, the said linkVariable method works for reference types too.., i.e,
Person x = new Person { Name = "Foo" };
var y = MagicUtilClass.linkVariable(() => x);
y.Value = new Person { Name = "Bar" };
Console.WriteLine(x.Name) //says Bar.
I am not sure how to achieve this in C# (not allowed to use unsafe code by the way)?
Appreciate ideas. Thanks.
Here is a full solution:
Usage:
To understand why this solution works, you need to know that the compiler transforms your code quite considerably whenever you use a variable inside a lambda expression (irrespective of whether that lambda expression becomes a delegate or an expression tree). It actually generates a new class containing a field. The variable x is removed and replaced with that field. The Usage example will then look something like this:
The “field” that the code retrieves is the field containing x, and the “constant” that it retrieves is the locals instance.