Skip to content

Understanding Events & Delegates.

Timothy

Asked May 26, 2008, 7:48 PM EDT1 answer
Share
LinkedInX

I have a simple question about Events.   Now I have just read this article:  http://www.c-sharpcorner.com/UploadFile/Ashush/DelegatesInCSharp02252008143634PM/DelegatesInCSharp.aspx

The article contains the following snippet of code as an example of how an event is coded.  My question is this:  Why not just bypass declaring an "Event" altogether and just have a delegate?  Instead just have code that says:  "if this delegate is referencing a function (i.e. not equal to null) then execute the function that it's pointing to.   Why the extra layer here?

C#
namespace EventsInCSharp
{
    public class MyClass
    {
        public delegate void MyDelegate(string message);
        public event MyDelegate MyEvent;

        //this method will be used to raise the event.
        public void RaiseEvent(string message)
        {
            if (MyEvent != null)
                MyEvent(message);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            MyClass myClass1 = new MyClass();
            myClass1.MyEvent += new MyClass.MyDelegate(myClass1_MyEvent);

            Console.WriteLine("Please enter a message\n");
            string msg = Console.ReadLine();

            //here is we raise the event.
            myClass1.RaiseEvent(msg);
            Console.Read();
        }
        //this method will be executed when the event raised.
        static void myClass1_MyEvent(string message)
        {
            Console.WriteLine("Your Message is: {0}", message);
        }
    }
}

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • Bechir Bejaoui
    0
    Smart question, the answer is simple too while the delegate is responsible to point the targeted method, the event type is responsible to trigger the code it self when a given action is performed so you can't ignore it
    0