I am learning lambda expression and delegates.While i try to execute the following ,I am getting error at the line which is marked bold line. (Error : Operator '+=' cannot be applied to operands of type 'Test.MessageDelegate' and 'lambda expression').Help me to handle lambda expression.
namespace Test
{
public delegate void MessageDelegate(string title,object sender,EventArgs e);
class Program
{
static event MessageDelegate logEvent;
static void Main(string[] args)
{
logEvent = new MessageDelegate(OnLog);
logEvent("title",Program.logEvent,EventArgs.Empty);
logEvent += (src, e) => { OnLog("Some",src, e); };
Console.ReadKey(true);
}
static void OnLog(string title, object sender, EventArgs e)
{
if (logEvent != null)
{
Console.WriteLine("title={0}", title);
Console.WriteLine("sender={0}", sender);
Console.WriteLine("arguments={0}",e.GetType());
}
}
}
}
asked Nov 15, 2009 at 17:37
user196546
2,6234 gold badges24 silver badges18 bronze badges
1 Answer 1
Since logEvent has MessageDelegate as its event handler, you'd need the left hand of the lambda expression (src, e) to match the signature of MessageDelegate
Change to (str, src, e) => OnLog(str, src, e)
answered Nov 15, 2009 at 17:41
David Hedlund
130k33 gold badges205 silver badges223 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
user196546
Suppose if i update my Main() as logEvent += (str, src, e) => { OnLog("One",Program.logEvent, EventArgs.Empty); }; logEvent += (str, src, e) => { OnLog("Two",Program.logEvent, EventArgs.Empty); }; (nothing is executed,how could i invoke it?)
user196546
I mean,consider Main() only has two lines as stated in the above comment.
David Hedlund
Hmm, I'm not sure I follow what you want to do here. The "+=" assigns a listener to a certain event. When logEvent happens, invoke OnLog. That line of code itself does not raise the log event, it only says what to do when the event is raised. To raise the log event, you should do 'if(logEvent != null) logEvent("title", this, null);' (or whatever you want to pass)
user196546
As i already assigned a listerner, just i invoked it as if( logEvent!=null) logEvent(null,null,null); .
lang-cs