How can I pass a ref to a lambda ? I've seend posts suggesting a delegate but I can't get it to work ..
I tried:
public class State<T>
{
public State() { }
public State(T t) { this.t = t; }
readonly object theLock = new object();
T t;
public void Lock(Action<ref T> action) { lock (theLock) action(ref t); }
}
however this does not compile, I get 'unexpected token ref'
I then tried:
public class State<T>
{
public State() { }
public State(T t) { this.t = t; }
readonly object theLock = new object();
T t;
public delegate void ActionRef<X>(ref X t);
public void Lock(ActionRef<T> action) { lock (theLock) action(ref t); }
}
Which compiles but I'm not able to use it
If I try:
var v = new State<int>(5);
v.Lock(t => t + 1);
I get Parameter 1 must be declared with the 'ref' keyword
If I try:
var v = new State<int>(5);
v.Lock(ref t => t + 1);
I get A ref or out value must be an assignable variable
How can I get this to work ? that is pass an Action to Lock which locks the lock and then calls the lambda with a ref ?
(tested in VS19 community preview .NET Core console app)
(this is different than Cannot use ref or out parameter in lambda expressions as there it's about a lambda using a ref in it's closure)