views:

220

answers:

1

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?

+5  A: 

You can use either lambda or anonymous delegate syntax - you just need to specify the type of the argument, and mark it as out:

public delegate bool CutoffDateDelegate( out DateTime cutoffDate );

// using lambda syntax:
CutoffDateDelegate d1 = 
    (out DateTime dt) => { dt = DateTime.Now; return true; };

// using anonymous delegate syntax:
CutoffDateDelegate d2 = 
    delegate( out DateTime dt ) { dt = DateTime.Now; return true; }

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.

LBushkin
I wouldn't consider it neither a bug nor an oversight. I think you should be explicit in saying it's an out or ref parameter. Why you can't just write `(out dt) => ...` is another matter.
Martinho Fernandes
That's actually what I was referring to - marking args explicitly out/ref is expected in C#. Having to declare the type of arguments for lambdas is less common, since in most cases the compiler does an excellent job inferring the type. I will update my post to make that clearer.
LBushkin