In the framework of the Framework we are creating, we need the following template:
public class BaseRenderer { Func<string> renderer; public BaseRenderer(Func<string> renderer) { this.renderer = renderer; } public string Render() { return renderer(); } } public class NameRenderer : BaseRenderer { public string Name{ get; set; } public NameRenderer () : base(() =>this.Name) {} }
As you can see, we create a lambda when the base constructor is called.
public class Program { public static void Main() { Console.WriteLine(new NameRenderer(){Name = "Foo"}.Render()); } }
Oddly enough, when trying to actually use a lambda, it throws a NullReferenceException (console application) or some kind of ExceptionEngineExceptionexception (web application in IIS).
I think the reason is that this pointer is not ready before calling the base constructor, so the lambda cannot capture this.Name at this point.
Shouldn't an exception be thrown at capture time instead of run time? Is this behavior described?
I can reorganize the code differently, but I think it is worth the comment.
Olmo Dec 09 '09 at 18:46 2009-12-09 18:46
source share