Tuesday, July 15, 2008

C# - Learning Events

Here is my simple attempt on implementing events in C#
Any comment would be appreciate.

using System;
namespace TutorialEvents
{
    delegate void PersonHandler(string information);

    class Person
    
        protected string name = "Anonymous";
        public static event PersonHandler PersonEvt;

        public void Process(string name)
        {
            OnPersonEvt(name);
        }

        protected void OnPersonEvt(string name)
        {
            string oldname;
            if (PersonEvt != null)
            {
                oldname = this.name;
                this.name = name;
                PersonEvt(String.Format("OldName : {0} - NewName : {1}", oldname, this.name));
            }
        }
    }

    class ControlNameChange
    {
        static void myPersonEvt(string message)
        {
            Console.WriteLine(message);
        }

        public void Subscribe()
        {
            Person.PersonEvt += new PersonHandler(myPersonEvt);
        }
    }

    class Test
    {
        public static void Main(String[] args)
        {
            Person p = new Person();
            ControlNameChange controlNameChange = new ControlNameChange();
            controlNameChange.Subscribe();
            p.Process("Henri");
            p.Process("Marcel");
            Console.ReadLine();
        }
    }
}

3 comments: