Events in C#

Goud.Kv
Posted by in C# category on for Intermediate level | Points: 250 | Views : 5772 red flag

C# is an Object-oriented programming language. C# comes with simplicity, expressiveness and great performance to meet the programmer productivity.

Introduction

So far, we have studied with delegates and compatibilities of delegates in C#. In this chapter, we are going to study events in C#.

Objective

The main objective of this article is to learn creating events from delegates in C# programming.

Events

Events are used to provide notifications to the clients. We use event keyword to perform such actions. The easiest way to declare an event is to use the event keyword in front of delegate.

For Example,
// Declaring delegate
public delegate void Pen(string color, string brand);

class Stationary
{
    // Declaring event
    public event Pen ColorChanged;
}
In the above code, we have first declared a delegate Pen() with "color" and "brand" as parameters.

Observe that in the Stationary class, we have declared an event "ColorChanged" by using our delegate Pen().

ColorChanged is now fully accessible with by any code with in Stationary class and treated as a delegate.

Any codes outside this class (Stationary) can only perform "-=" and "+=" operations on our ColorChanged event.

How do events work inside the compiler?

A very nice question and here we are with the answer. While declaring event, compiler performs three operations (processes) as follows,

Let's recall our above event as example,
class Stationary
{
    public event Pen ColorChanged;
}
1st Step:
After the declaration of an event, compiler translates the declaration to its understandable mode something like below,
Pen _colorChanged;  // This is a private delegate

public event Pen ColorChanged
{
    add    { _colorChanged += value; }
    remove { _colorChanged -= value; }
}
In the above conversion, there is a delegate field _colorChanged which is created by the compiler. We can see add and remove keywords which denote explicit event accessors. These are similar to the property accessors.

2nd Step:
Now, compiler takes a deep look into our Stationary class for any references that performs operations other than -= and +=. If any found, it will redirect them to its private delegate field _colorChanged (compiler created field).

3rd Step:
Finally, compiler translates the += and -= operations on the event to the event's add and remove accessors.

Note: This makes the behavior of += and -= in case of events. In any other situations, it is simply + and - followed by an assignment.

How to use an Event?

Events are mostly used in graphical user interfaces (GUI). They can have many handlers. Let's take an example program of creating events,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Example
{
    public delegate void Pen(); // Declaration of delegate

    class Program
    {
        public static event Pen Colors;  // Declaration of event

        static void Main()
        {
            Colors += new Pen(BluePen);  // Adding BluePen to Colors
            Colors += new Pen(RedPen);   // Adding RedPen to Colors 
            Colors += new Pen(BlackPen); // Adding BlackPen to Colors

            Colors.Invoke();             // Invoking the event Colors
        }

        static void BluePen()
        {
            Console.WriteLine("This is Blue pen");
        }

        static void RedPen()
        {
            Console.WriteLine("This is Red pen");
        }

        static void BlackPen()
        {
            Console.WriteLine("This is Black pen");
        }
    }
}
In the above example, we have created an event using delegate. At first we declared a delegate Pen(). With that, we have declared the event (Colors) using event modifier.

In our program, we have three static methods BluePen(), RedPen() and BlackPen().

In the Main() method, we are adding all the methods to the events by using += operator. It will store all the methods in its event list. We can also remove any one by using -= operator.

Colors.Invoke() will invoke the event Colors.

Press Ctrl + F5 to run this program which gives you the following output in your console,


Conclusion

In this article, we have seen declaring events from delegates and how does an event work inside the compiler. Hope you understand.

Thank you for reading.

Regards,
Krishna

Page copy protected against web site content infringement by Copyscape

About the Author

Goud.Kv
Full Name: Krishna Vamshi Goud
Member Level: Gold
Member Status: Member,MVP
Member Since: 2/12/2014 2:34:09 AM
Country: India
Thanks & Regards, Krishna


Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)