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.
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With