Similar to how lambda expressions with free variables work I would like to implement my own closure class that captures some method parameter.
public class Closure<TObject, TVariable>
{
public TVariable Variable { get; set; }
public Func<TObject, bool> Predicate { get; set; }
}
Then I have some class that works with DateTime instances. One of the methods that should use this closure class is this:
// Original Version
public IEnumerable<Item> GetDayData(DateTime day)
{
this.items.Where(i => i.IsValidForDay(day));
}
I would like to convert it to use Closure class. The problem is that I would like to reuse (performance reasons) my Closure class instance:
private Closure<Item, DateTime> closure = null;
public IEnumerable<Item> GetDayData(DateTime day)
{
if (closure == null)
{
this.closure = new Closure<Item, DateTime>() {
Variable = reference of "day" param, <=== HOW ????????
Predicate = i => i.IsValidForDay(this.closure.Variable)
}
}
this.items.Where(this.closure.Predicate);
}
In order for me to reuse the same Closure instance I would have to not store the value of the parameter (into closure’s Variable field) but rather method parameter’s reference pointer. So the next time this method gets called closure’s Variable would actually point to the correct value to be used.
How am I supposed to do this?
A similar thing is done when compiler generates classes that capture lambda expression free variables. I’ve been looking at decompiled code (using Reflector), but I don’t seem to understand how that’s done…
Your example is slightly wrong (also this probably wont work, but the semantics/intent is correct):