Unraveling Delegates & Events

This article briefs about Delegates and focuses on differentiating Delegates & Events

Contents

Introduction

What are Delegates

Typesafe Delegates

Declaring, Instantiating and Invoking Delegates

Events

Conclusion

Introduction

Delegates & Events are often the most ignorant pieces in the .NET Framework. Rumor has it; they instill fear in the curious minds by their sheer complexity. I studied a great deal of articles in an effort to demystify the unknown, but I really found out there wasn't anything colossal here. Through my article, I will try my hand at exploring the nature of Delegates & Events. Now let’s get down to business.

What are Delegates

If you ask anybody, they would say:

Delegates are similar to Function pointers in C/C++.

Well said, but what are function pointers.

Function pointers are the pointer variables that point to a memory address of a function. So invoking that function pointer would call simply call the underlying function.

DataGrid’s ItemDataBound is the event of type DataGridItemEventHandler Delegate pointing to function DataGrid1_ItemDataBound.

Do not indulge into this right now as I will come to Events later on in the article.

Typesafe Delegates

Are Delegates Any Different from their C/C++ Counterparts (Function Pointers)

Yes, delegates in .NET Framework are typesafe. This means that Delegate signature should match that of the function it points to (encapsulates).

You will get a compile-time error if that’s not the case.

On the other hand, a function pointer in C points to a memory location but it knows nothing about the parameters and the return type of the function unlike delegates.

Declaring, Instantiating and Invoking Delegates

Declaration

Let’s declare a simple delegate:

publicdelegatebool SmartDelegate(string name, int salary);

This delegatesignature signifies that it will encapsulate methods with return type as booland parameters as stringand int.

The function that this delegatereferences would look something like this:

publicbool Myfunc(string name, int salary)

So What Exactly Happens When a Delegate Declaration is Executed?

A delegatedeclaration is a class declaration that mimics a function-like declaration. In other words, a class is defined that is derived from a MulticastDelagate class and can be actually deciphered as:

publicclass SmartDelegate : System.MulticastDelegate

Instantiation

SmartDelegate smartDelegate = new SmartDelegate(MyFunc);

Notice how you instantiate a delegate, just like you would instantiate a class, simply because a delegateis a class.

You can add to the delegates invocation list by using the “+=” operator.

Instantiation of a delegateincludes passing the function name (MyFunc) in its constructor. Notice, you do not include the round braces of the function.

Excluding the braces simply means passing the address of the function.

Note: An instance of a delegatecan refer to any instance or staticmethod, provided the signature of the method matches the signature of the delegate.

Invoking Delegate

Simply call the delegateinstance:

smartDelegate();

So What Happens When You Actually Call the Delegate Instance?

Invoking a delegategets translated as follows:

sampleDelegate.Invoke()

The Invoke function calls the function (MyFunc) in turn using the address of the function stored in the delegateinstance.

Events

Let’s shift our energy to events.

Events are the outcome of an action. Yes, they are but there is more to this Delegates & Events tale. Infact, my prime reason to write this article was to explore the difference between the two. We could have simply done away with just having delegates, but why do we need events.

Events are really restricted delegates.

Playing with Events

Let’s start by declaring an event.

publicstaticevent SmartDelegate SmartEvent;

Again adding a target to an eventis a similar procedure to that of delegates:

if u can provide an example of when and why to use events and delegates,then it would be very helpful.Anyway thanks for putting all these tedious things together and explaining it in human language.uss

nice article . I would only say, that I guess the C function callbacks are also typesafe (never worked with C, only C++).

Anyway, what I am missing in nearly every description of the events/delegates is a consequences for the object lifetimes in garbagge collector - I mean some description, that by attaching event to the class, the class cannot be marked for collection until the event is detached or the event-source class is marked as well. Important especially when you attaching to events on the singletone and you forget to detach (-=). This can cause the resource leaks. dtto for delegates.

Your example "Now a certain Class Client accesses just the delegate field." with the following code in the main method:
ClassA objA = new ClassA();
objA.smartDelegate += new SmartDelegate(MyFunc1); //statement 1
objA.smartDelegate = new SmartDelegate(MyFunc2); //statement 2

There won't be a output "MyFunc2" because no one calls smartDelegate() or am I wrong?
I think it has to be like that to get a output:
ClassA objA = new ClassA();
objA.smartDelegate += new SmartDelegate(MyFunc1); //statement 1
objA.smartDelegate = new SmartDelegate(MyFunc2); //statement 2
objA.smartDelegate();

There are C# Tutorials from MSDN, one for delegates, one for events and many other topics as well.
Some of these have been quite useful for me - sometimes I got better explanations than from good books.

I have tried to use the Delegate / Events as you have shown in your article. But when the event is invoked from the class, it throws a Null reference exception. But when I declare the event as Static, it works. Please advice.