This question already has an answer here:
I have a delegate defined in my code:
public bool delegate CutoffDateDelegate( out DateTime cutoffDate );
I would like to create delegate and initialize with a lambda or anonymous function, but neither of these compiled.
CutoffDateDelegate del1 = dt => { dt = DateTime.Now; return true; }
CutoffDateDelegate del2 = delegate( out dt ) { dt = DateTime.Now; return true; }
Is there way to do this?
You can use either lambda or anonymous delegate syntax - you just need to specify the type of the argument, and mark it as out:
While explicitly declaring arguments as ref/out is expected, having to declare argument types in lambda expression is less common since the compiler can normally infer them. In this case, however, the compiler does not currently infer the types for out or ref arguments in lambda/anon expressions. I'm not certain if this behavior is a bug/oversight or if there's a language reason why this must be so, but there's an easy enough workaround.
EDIT: I did a quick check in VS2010 β2, and it still looks like you have to define the argument types - they are not inferred for C# 4.