Software & Finance





C# - Events





Refer to Delegates and multicast delegates before reading about Events.

Special type of delegates are called events. Events are defined with the keyword called event.

        public delegate void Shape();
        public event Shape ShapeEvent;


Events are used in many places. A typical example would be which call back function needs to be used on a mouse click event. Look at the sample code and it is easy to understand.

 

Source Code


using System;

using System.Collections.Generic;

using System.Text;

 

namespace Basics

{

    class Drawing

    {

        public delegate void Shape();

        public event Shape ShapeEvent;

        public void Rectangle()

        {

            Console.WriteLine("This is Rectangle");

        }

 

        public void Square()

        {

            Console.WriteLine("This is Square");

        }

 

        public void Circle()

        {

            Console.WriteLine("This is Circle");

        }

 

        static void Main(string[] args)

        {

            Drawing d = new Drawing();

 

            // Shape is like a fuction pointer in C++

            // Shape [] is assigned with 3 functions with same function sigature

            Shape [] parray = { new Shape(d.Rectangle),

                                new Shape(d.Square),

                                new Shape(d.Circle)

            };

 

          // Event is assigned with all 3 functions.

              

          for (int i = 0; i < 3; i++)

          {

              d.ShapeEvent += parray[i];

          }


// When the event is fired all 3 functions are invoked.  

          d.ShapeEvent();

        }

    }
}

Output


 

This is Rectangle

This is Square

This is Circle