Question

At Test.AEventHandler gives me error : non-invocable ... cannot use as method. I cant see where I am wrong :( .

Can you tell me why is not working? Thanks!

Class Program
{
    static void Main(string[] args)
    {
        Test first = new Test();
        first.send += Test.AEventHandler(onMessage);
    }

    public void onMessage(Message m)
    {
        Console.Writeln("It works!!!!");
    }

    ....
}

Class Test
{
    public delegate void AEventHandler(Message m);
    public event AEventHandler send;

    public void msg1(Message m)
    {
        if(send!=null)
            send(m);
    }

    ......
}

Note: Message is a type define by me...

If you can, please fix my code.

Was it helpful?

Solution

First change your onMessage method to static because Main method is static.You can't access a non-static method from inside static context:

public static void onMessage(Message m)

Then attach your event handler like this:

 first.send += new Test.AEventHandler(onMessage);

Or short version:

 first.send += onMessage;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top