I'd like if I could make a reference that will always point to that specific variable rather than to the object (or memory location more accurately) that the variable is currently representing.
As an example let's say I have the following program, I want to create a reference to MyClass a so that it always returns whatever value is in MyClass a at all times, even if that value changes. I have some code that looks like.
class MyClass
{
public int value = 0;
}
class Program
{
static MyClass saved; //maintained and used by the following two functions
static void StoreReference(MyClass input)
{
saved = input;
}
static void SetValue()
{
saved.value = 42;
}
static void Main(string[] args)
{
//A couple arbitrary classes I'd like to have references to
MyClass a = new MyClass();
MyClass b = new MyClass();
StoreReference(a);
a = b;
SetValue();
Console.Write(a.value); //should print 42, instead prints 0 since it reads in the original object a was set to
}
}
Is there anything that can do this in C#, or anything that can prevent the variable from being assigned to a new memory location (so that the above code would return an error at a = b)?
You can check whether
saved
already has a value or not: