Search This Blog

Tuesday, July 16, 2013

Events C#


Events in C# are based on the delegate model.
To declare an event in a class the delegate type for the event must be declared.

Events use the publisher-subscriber model.

A publisher is an object that contains the definition of the event and the delegate.
A subscriber is an object that accepts the event and provides an event handler.




Example:


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public class Event
        {
            private int value;
            public delegate void EventHandler(int v);
            public event EventHandler ValueChanged;

            protected virtual void OnValueChanged()
            {
                if (ValueChanged != null)
                {
                    ValueChanged(value);
                }
            }
            public Event()
            {
            }
            public void SetValue(int n)
            {
                if (value != n)
                {
                     value = n;
                    OnValueChanged(); // raise event
                }
            }
        }
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            Event ev = new Event();
            ev.ValueChanged += ev_ValueChanged;
            ev.SetValue(2);
            ev.SetValue(3);
        }
        void ev_ValueChanged(int v)
        {
           MessageBox.Show("Event value : " + v.ToString()); 
        }
     }
}