Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delegate.Combine and lambda expression

Suppose i have this delegate's declaration:

    private delegate UInt32 Feedback(UInt32 value);

And here i try to use it with lambda expression

    feedback = (Feedback)Delegate.Combine(feedback, 
        value => { Console.WriteLine("Lambda item = " + value); return 0; });

But i get error: Cannot convert lambda expression to type 'System.Delegate' because it is not a delegate type

But it works this way

    feedback = (Feedback)Delegate.Combine(feedback, 
        new Func<UInt32, UInt32>(value => { Console.WriteLine("Lambda item = " + value); return 0; }));

I have thought that C# compiler must do it itself.

like image 332
Yola Avatar asked Jan 18 '26 16:01

Yola


2 Answers

feedback = (Feedback)Delegate.Combine(feedback, 
    (Feedback)(value => { Console.WriteLine("Lambda item = " + value); return 0; }));

You must explicitly say the type of a lambda function, otherwise the compiler doesn't know what type it has. For example see http://blogs.msdn.com/b/jaredpar/archive/2007/12/14/c-lambda-type-inference.aspx

One of the limitations of C# type inference is that you cannot use it to infer the type of a lambda expression. For example, the following code will not compile

var f = () => 4;
like image 171
xanatos Avatar answered Jan 21 '26 04:01

xanatos


Lambda expressions do not have type in C# unless you cast them.It's because one lambda can be convertible to more than one delegate type so compiler can't decide which one to choose.And also there is no way to determine what are the type of lamda arguments since you are not specifying them.

like image 35
Selman Genç Avatar answered Jan 21 '26 05:01

Selman Genç