9

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?

dorn
  • 91
  • 1
  • 2
  • 2
    Realize this is kind of old, but I don't think it's a duplicate. The linked question is about using the parent(?) function's out parameter inside the anonymous function, whereas this one is about declaring an anonymous function that has it's own out parameter. – Salvador May 17 '15 at 01:17

1 Answers1

19

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
  • 129,300
  • 32
  • 216
  • 265
  • 5
    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. – R. Martinho Fernandes Jan 02 '10 at 04:11
  • 1
    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 Jan 02 '10 at 04:16
  • 2
    just stumbled across this - note that if you have multiple parameters, you have to declare all of their types explicitly, even if they're not all ref/out – drzaus Apr 25 '12 at 17:58