Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write a lambda or anonymous function that accepts an out parameter [duplicate]

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?

like image 690
dorn Avatar asked Jan 02 '10 04:01

dorn


1 Answers

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.

like image 99
LBushkin Avatar answered Sep 28 '22 02:09

LBushkin