Innovation Through Knowledge

Main menu

What is Delegates and Events in C#.Net

This tutorial describes some basics about some of the additional features of C# language namely Delegates and Events. These new constructs are used in object-oriented programming languages like C# and Java.

Delegates in C# .Net:

In languages like C/C++ there is a feature called callback function. This feature uses Pointers to Functions to pass them as parameters to other functions . Delegate is a similar feature but it is more safe and possible to use in object-oriented constructions of programming language. It needs the method’s name and its parameters (input and output variables) when we create a delegate. But delegate is not a standalone construction it’s a class. Any delegate must be inherited from base delegate class of .NET class library. This is class called System.MultycastDelegate. So, now please have a look at the following example:

In this example we create three delegates of FigureDelegate type and attach to these elements our three methods from Figure class. Now every delegate keeps the address of the attached function. The last line of code is very interesting, here we create a delegate of base type (MulyCastDelegate) and attach three of our already created delegates. It is an allowed construction because every delegate inherited from base type can keep more than one pointer to function. Since, it can contain a list of addresses to methods.

Events in C# .Net:

Delegate is a very useful construct in C# language as it can define and use function names at runtime not at compile time. But the main goal of using delegates is using them into events model. Events are the actions of the system on user manipulations (e.g. mouse clicks, key press, timer etc.). To understand the usage of delegates for event model, the previous examples are used here. We should add to our Figure class next things:

Now we have a delegate declared and event that uses this delegate’s type. In every function we should call our event. It is not yet very clear why we should use such construction, but the next code snippet should explain it clearly:
static void Main(string[] args)
{

So, in the main function we should create an object of figure class and attach event handler to the method OnFigureInverted. And when we call any of invert methods the event is fired and it calls our event handler. The application will print the following string into the console:

Figure was inverted by x-axis
Figure was inverted by z-axis

There was simple examples of using delegates and events and should be treated as a starting point to learn it more yourself.