Hi I am learning event handling. I have defined my own event and raise it in class MyEventHandle and have defined a method to handle this event in class HandleEvent. In class MyEventCall I tried to handle my difned event but it throws an exception at runtime. I do not understand where I did the mistake. Can anyone help me in this issue. The entire code is given below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EventHandling
{
    public delegate void LoopEventHandle(int number);

    public class MyEventHandle
    {
        public event LoopEventHandle lopEvent;

        public MyEventHandle()
        {
            for (int i = 100; i > 1; i--)
            {
                if (i % 5 == 0)
                {
                    if (lopEvent != null)
                    {
                        lopEvent(i);
                    }
                }
            }
        }       
    }

    public class HandleEvent
    {        
        public void DisplayMessage(int i)
        {
            Console.WriteLine("The number is {0} : ", i);
        }
    }

    public class MyEventCall
    {
        public MyEventCall()
        {            
            MyEventHandle myEvent = new MyEventHandle();
            HandleEvent handleEvent = new HandleEvent();

            myEvent.lopEvent += new LoopEventHandle(handleEvent.DisplayMessage);

            Console.ReadKey();
        }
    }
}

Thanks in advance.

Here's the link to an MSDN article on designing custom event handlers. Here's the link to an MSDN article on designing events. It seems there are several things missing from your code.

I don't see anything "missing", I also don't see where an exception would be thrown (other than not having a Main() method defined; which would be a compile-time exception anyways). Could you post the exception you are getting?

Also, your execution order won't work... You're attempting to raise the event before a handler is added. In other words, you are attempting to raise an event in the MyEventHandle constructor, which executes from line 41, but you don't define a handler until line 44.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.