Events

As I mentioned in my delegates article, it took me quite a lot of time to understand the importance of delegates and events. For some time, I was confused as to when would I need events. I understood the button click events but was not able to come up with a concrete non-UI scenario in which I would like to use events. In this blog post, I will share a scenario which made it very easy for me to understand events. I hope this makes it simple for you too - 

Let's say our scenario is that there is a Person class and the Person class has an age property and we want something to happen when the Person's age changes. To put the responsibility on the consumer class to call a function everytime the age changes would be an error-prone approach. So we don't want to take that route. Let's say that on top of that, we still want the consumer class to be able to define what that change action should be. So basically, we are saying that, Person class should define the event, however, the implementation would be taken care by the consumer class. How can we achieve this?

public class A02Events
    {
        public static void DoSomething()
        {
            Person p = new Person { Name = "Peter", Age = 20 };
            p.AgeChanged += new Action<int>(p_AgeChanged);

            p.Age = 30;
            System.Threading.Thread.Sleep(1000);
            p.Age = 31;
            System.Threading.Thread.Sleep(1000);
            p.Age = 32;
            System.Threading.Thread.Sleep(1000);
            p.Age = 33;
        
        }

        static void p_AgeChanged(int arg)
        {
            Console.WriteLine("Age changed to " + arg);
        }
    }

    public class Person
    {
        public string Name { get; set; }

        private int m_age;
        public int Age
        {
            get { return m_age; }
            set 
            {
                if (m_age != value)
                {
                    m_age = value;
                    if(AgeChanged !=null)
                        AgeChanged(value);
                }
            }
        }

        public event Action<int> AgeChanged;
    }
In this example -
  • In the Person class we declare an event. Its an Action<int> delegate, meaning that it will take int as input and will return void.
  • In the A02Events class, we say that for this event call the method p_AgeChanged, everytime age changes. This call is made in the setter for Age property inside Person class.
  • Then, just for demonstration purposes, Peter ages very fast, almost at the rate of 1 year/1 sec. Everytime, the age is changed p_AgeChanged event is fired.
The output looks like -

No comments: