1

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());
            }
        }
     }

 }

1 Answer 1

5

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)

Sign up to request clarification or add additional context in comments.

4 Comments

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?)
I mean,consider Main() only has two lines as stated in the above comment.
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)
As i already assigned a listerner, just i invoked it as if( logEvent!=null) logEvent(null,null,null); .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.