An impossible primitive for databinding
Tuesday 23 March 2010 - Filed under Uncategorized
Something that often comes up in UI programming is how to bind UI controls to backend data without writing a pile of code – and preferably without using reflection. Here’s an attempt (thwarted by the compiler, unfortunately) at capturing a C# ref parameter in closures so it can be passed around, stored, etc. It seems reasonable, and even useful, at a first glance:
class Binding<T>
{
Action<T> SetValue;
Func<T> GetValue;public T Value
{
get { return GetValue(); }
set { SetValue(value); }
}public Binding(ref T t)
{
SetValue = u => t = u; // not allowed.
GetValue = () => t; // not allowed.
}
}
Turns out that the compiler refuses to lift ref or out parameters into a closure – for good reason. If we were to allow this, then we’d have to rewrite the callers of Binding.ctor to lift their arbitrary ref expressions into the closure. That’s too much of a contortion, especially when those callers could be in another assembly…
So there you go: an interesting approach that doesn’t work.
2010-03-23 » admin