SqlClr and anonymous delegates

time to read 2 min | 205 words

Okay, I'm playing around with SqlClr (doing runtime DDL stuff, mainly), and I discovered that SqlClr and anonymous delegates don't play along very well. The issue is that code like this:

CallWithAction(delegate(DateTime dt) { return dt; } );

Is actually translated to something like this:

if(ClassName.<> HiddenFieldName == null) 
            ClassName.<> HiddenFieldName = new SomeDelegate(HiddenMethodName);
CallWithAction(ClassName.<> HiddenFieldName);

And that causes problem with the SqlClr, since the method is trying to store into a static field, which doesn't seem to be allowed on the safe level (which I really don't want to pass.)

It doesn't happen if the anonymous method uses local variables, since then the compiler generate a completely new class. Just a little gotcha that I would've never solved without Reflector.