in Uncategorized

Anonymous methods cannot access ref/out parameters

Just throwin’ this post up because I was suprised by a compiler error I just received and noticed that there were only two search results for it when I looked for an explanation. Basically the problem is exactly what the title of this post says: you can’t access ref/out parameters from within an anoymous delegate. The exact C# compiler error you’ll get is:

Cannot use ref or out parameter ‘yourParameterNameHere’ inside an anonymous method block

At first I was like “hmm, that’s pretty lame… wonder why that would be?”. Then I thought about the actual implementation of anonymous delegates and the way that┬ávariables are “enclosed”, which is detailed very nicely by this MSDN Magazine article, and it all made sense. Obviously they have no way to do a “pointer to a pointer” on the class that the compiler emits since there’s no such concept available in safe, managed code.

That said, the work around is pretty easy: in your method that takes a ref/out parameter you just need a local variable which you work with internally and assign that reference to the parameter when the work is done.

Leave a comment

Comment