Store a reference in another variable

.net, c#, reference

Solution

Update in 2022: while this likely isn't a particularly suitable feature for implementing Undo, C# 7 introduced ref locals and ref returns, and C# 11 plans to allow these to be stored in ref fields.

Other than that:

Standard safe C# does not support this at all. The underlying framework has almost all of the necessary concepts, but they aren't exposed in the C# language. But even then, such a reference can't be stored in a field.

The best you can have is to wrap it in some class that uses delegates. This is obviously rather expensive in comparison, but unless you are modifying things in a tight loop this might be good enough:

class VarRef<T>
{
    private Func<T> _get;
    private Action<T> _set;

    public VarRef(Func<T> @get, Action<T> @set)
    {
        _get = @get;
        _set = @set;
    }

    public T Value
    {
        get { return _get(); }
        set { _set(value); }
    }
}

And then use it like this:

var myVar = ...
var myVarRef = new VarRef<T>(() => myVar, val => { myVar = val; });

...

myVarRef.Value = "47";
Console.WriteLine(myVar); // writes 47

Problem

I've been searching around a bit, but I can't find any way to store a reference to another variable in a certain variable. I'm trying to make a class to undo things done by the user; ``` class UndoAction { public object var; public object val; public UndoAction(ref object var, object val) { this.var = var; this.val = val; } public static List<UndoAction> history = new List<UndoAction>(); public static void AddHistory(ref object var, object val) { history.Add(new UndoAction(ref var, val)); } } ``` I guess you can see what I'm trying to achieve here. The problem I ran on; ``` this.var = var; ``` doesn't store the reference, but the value of the referenced 'var'. How can I store the reference itself, so I can simply run; ``` this.var = val; ``` to "undo" an action, in my case?

Original source

Related problems