C# Simple Delegate and Event Example | C# Examples
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#.

Usage:

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

Example:

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

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

Leave a Reply

Your email address will not be published. Required fields are marked *