Delegates and Events in C#

using System;
using System.Collections.Generic;
using System.Text;

namespace CSharpBasics
{
    //An interesting and useful property of a delegate is that
    //it does not know or care about the class of the object that
    //it references. Any object will do; all that matters is that
    //the method's argument types and return type match the delegate's.
    //This makes delegates perfectly suited for "anonymous" invocation. 

    public delegate void MyDelegate();
    public delegate void MyDelegateParam(string s);
    public delegate string MyDelegateParamReturn(string s);

    public delegate void MyDelegateMulti();

    class Delegates
    {
        public void fun1()
        {
            Console.WriteLine("From delegate_fun1");
        }

        public void fun2(string s)
        {
            Console.WriteLine("From delegate_fun2 :" + s);
        }

        public string fun3(string s)
        {
            return ("From delegate_fun3 :" + s);
        }

        public void fun4(string s)
        {
            Console.WriteLine("From delegate_fun4 :" + s);
        }

        public void multicast_fun1()
        {
            Console.WriteLine("MultiCast Funtion 1");
        }

        public void multicast_fun2()
        {
            Console.WriteLine("MultiCast Funtion 2");
        }

        public MyDelegate del;
        public MyDelegateParam del2;
        public MyDelegateParamReturn del3;
        public MyDelegateMulti del4;
        public Delegates()
        {
            del = new MyDelegate(fun1);
            del2 = new MyDelegateParam(fun2);
            del3 = new MyDelegateParamReturn(fun3);

            //Multicast
            del4 += new MyDelegateMulti(multicast_fun1);
            del4 += new MyDelegateMulti(multicast_fun2);
            del4 += new MyDelegateMulti(functionsForDelegate.multicast_fun1);

            //Anonymous funtions
            del4 += new MyDelegateMulti
                (delegate()
                {
                    Console.WriteLine("Multicast function From Anonymous function");
                });
        }

    }

    class functionsForDelegate
    {
        public static void multicast_fun1()
        {
            Console.WriteLine("Multicast function from other class");
        }
    }

    //Events
    //Few Events Key points to remember
    /*
    1.Event Handlers in the .NET Framework return void and take two parameters.
    2.The first paramter is the source of the event; that is the publishing object.
    3.The second parameter is an object derived from EventArgs.
    4.Events are properties of the class publishing the event.
    5.The keyword event controls how the event property is accessed by the
      subscribing classes.
    */

    class events
    {
        public event MyDelegateParam myEvent;

        protected void onMyEvent(string s)
        {
            if (myEvent != null)
                myEvent(s);
        }

        public void executeEvents()
        {
            Delegates d = new Delegates();

            this.myEvent += new MyDelegateParam(d.fun2);
            this.myEvent += new MyDelegateParam(d.fun4);

            this.onMyEvent("Hello");
            this.onMyEvent("Bye");
        }
    }

    class MyEventArgs
    {
        public readonly string c;
        public MyEventArgs(string _c)
        {
            this.c = _c;
        }
    }

    class CharChange
    {
        private string _c;
        public delegate void charChangeHandler(object charchange, MyEventArgs e);

        public event charChangeHandler charChangeEvent;

        protected void OnCharChange(object charchange,MyEventArgs e)
        {
            if (charChangeEvent != null)
            {
                charChangeEvent(charchange, e);
            }
        }

        public void run()
        {
            //enter digit to break the loop
            string c;
            _c = string.Empty;
            Console.Write("Enter Line(Enter Empty Line To exit loop) : ");
            c = (string)Console.ReadLine();
            while (c != string.Empty)
            {
                if (c != _c)
                {
                    MyEventArgs mea = new MyEventArgs(c);
                    OnCharChange(this, mea);
                }
                _c = c;
                Console.Write("Enter Line(Enter Empty Line To exit loop) : ");
                c = Console.ReadLine();
            }
            Console.WriteLine("Loop terminated...");
        }
    }

    /*
    The publisher and the subscribers are decoupled by the delegate.
    This is highly desirable as it makes for more flexible and robust code.
    The string can change without breaking any of the subscribing classes.
    The subscribing classes can change how they respond to string changes without
    breaking the charchange class.
    The two classes spin indepentdently of one another, which makes for code that
    is easier to maintain.
     */
    class subscriber1
    {
        public void subscribe(CharChange c)
        {
            c.charChangeEvent += new CharChange.charChangeHandler(c_charChangeEvent);
        }

        void c_charChangeEvent(object charchange, MyEventArgs e)
        {
            Console.WriteLine("From subcriber 1 : " + e.c.ToString());
        }
    }

    class subscriber2
    {
        public void subscribe(CharChange c)
        {
            c.charChangeEvent += new CharChange.charChangeHandler(c_charChangeEvent);
        }

        void c_charChangeEvent(object charchange, MyEventArgs e)
        {
            Console.WriteLine("From subcriber 2 : " + e.c.ToString());
        }
    }

    class program
    {
        static void main(string[] args)
        {
            Console.WriteLine("****************Delegates/Events*****************");

            Console.WriteLine("");
            Console.WriteLine("                                 Delegates");
            Console.WriteLine("");
            Delegates deleg = new Delegates();
            deleg.del();
            deleg.del2("From Main");
            Console.WriteLine(deleg.del3("From Main"));

            deleg.del4();

            Console.WriteLine("");
            Console.WriteLine("                                 Events");
            Console.WriteLine("");

            events evnts = new events();
            evnts.executeEvents();

            //Complex events
            Console.WriteLine("");
            Console.WriteLine("                             Complex Events");
            Console.WriteLine("");

            CharChange charc = new CharChange();
            subscriber1 s1 = new subscriber1();
            subscriber2 s2 = new subscriber2();
            s1.subscribe(charc);
            s2.subscribe(charc);
            charc.run();

        }
    }
}

OUTPUT

****************Delegates/Events*****************

                                 Delegates

From delegate_fun1
From delegate_fun2 :From Main
From delegate_fun3 :From Main
MultiCast Funtion 1
MultiCast Funtion 2
Multicast function from other class
Multicast function From Anonymous function

                                 Events

From delegate_fun2 :Hello
From delegate_fun4 :Hello
From delegate_fun2 :Bye
From delegate_fun4 :Bye

                             Complex Events

Enter Line(Enter Empty Line To exit loop) : 3
From subcriber 1 : 3
From subcriber 2 : 3
Enter Line(Enter Empty Line To exit loop) : 1
From subcriber 1 : 1
From subcriber 2 : 1
Enter Line(Enter Empty Line To exit loop) : 4
From subcriber 1 : 4
From subcriber 2 : 4
Enter Line(Enter Empty Line To exit loop) :
Loop terminated...
Tags: , , ,

Leave a Reply

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

*
*