14 Jun

C# Simple Delegate and Event Example

A delegate is a reference type like the other reference types. But instead of referring to an object, a delegate refers to a method. Following example shows event and delegate usage in C#.


            EventDelegateExample e = new EventDelegateExample();
            e.ShowedMessage += new EventDelegateExample.MyCustomEventHandler(delegate(string message) 
                    Console.WriteLine("A new message:" + message);


    class EventDelegateExample
        public delegate void MyCustomEventHandler(string message);
        public event MyCustomEventHandler ShowedMessage;

        public void ShowNewMsg(string s)
            if (ShowedMessage != null)