Bala
Bala

Reputation: 166

C# EventHandler

class Program
{
    public delegate void mydel();
    public static event mydel myevent;

    static void del()
    {
        Console.WriteLine("Called in del");

    }

    static void Main(string[] args)
    {
        myevent = del;
        myevent += new EventHandler(del);
        myevent();
        Console.ReadLine();

    }
}

myevent += new Eventhandler(del); This line doesn't work...It generates Error "No overload for 'del' matches delegate 'System.EventHandler' "

Upvotes: 1

Views: 508

Answers (3)

Irfan
Irfan

Reputation: 2771

Simplify your code, then it will work like magic!

static void Main(string[] args)
{
   myevent += del;
   myevent();
   Console.ReadLine();
}

Upvotes: 0

No Idea For Name
No Idea For Name

Reputation: 11577

the problem is with the lines

myevent = del;
myevent += new EventHandler(del);

just remove them and replace the syntex.

the right syntex to register to event is:

myevent += new mydel(del);

or

myevent += del;

but not as you did

myevent = del;

you should also always check before calling an event that it isn't null.

so your code should be:

class Program
{
    public delegate void mydel();
    public static event mydel myevent;

    static void del()
    {
        Console.WriteLine("Called in del");

    }

    static void Main(string[] args)
    {
        myevent += new mydel(del);

        if(myevent != null)
        {
           myevent();
        }

        Console.ReadLine();

    }
}

to learn more on event and registering read here:

The += operator is used to add the delegate instance to the invocation list of the event handler in the publisher. Remember, multiple subscribers may register with the event. Use the += operator to append the current subscriber to the underlying delegate's invocation list.

Upvotes: 0

Alessandro D'Andria
Alessandro D'Andria

Reputation: 8868

Simply add the handler:

    static void Main(string[] args)
    {
        myevent += del;
        myevent();
        Console.ReadLine();

    }

Your event is not an EventHandler. Your event is of type mydel.

public delegate void mydel(); // declaring the delegate
public mydel myevent; // declaring an event of type mydel with signature void mydel()

public void del() {...} // this method fit the delegate

// myevent += new EventHandler(del); // myevent is not an EventHandler

Upvotes: 1

Related Questions