What are Delegate and Multicast delegate in C#? What are event and what is difference between delegate and event in c#?

Delegates are function pointer. Delegate generally serves below purposes.

1> Callback

2> Event handling

A delegate is special type of object which contains detail of method rather than data. In simple word it will encapsulate one method or more than one method. It has same signature as method which it will call. Same signature means, delegate can point to method which has

1>same return type as of delegate.

2>number, order and type of parameter in method should match to delegate.

Delegate1

As you can see above delegate can be declared inside class and outside class.

First you declare delegate and then create instance of it. Then you call delegate using instance of delegate. In above image I have tried to show different ways you can use to instantiate delegate. We have called Instance method and static method using delegate instance in above example.

Note: You can also call delegate by using Invoke function.

Printobj1.Invoke();

PrintVal1.Invoke(4);

Multicast delegate

 If Delegate is pointing to more than one function then it is called multicast delegate. All the function you will attach to  delegate will have same signature as delegate.

Delegate1.1

In above image we first declared “MessageLogger” delegate. Then we instantiate it. Then we attach multiple functions to instance of delegate. When we call instance, messageLogger(“Hello world”);.

Now methods will get called in order in which they were attached. Method’s will get called in below order.

LogInFile(string message)

LogInDB(string message)

LogInServer(string message)

Note: As you see above, first method called is “LogInFile(string message)”,as we had passed this method in constructor of delegate(“MessageLogger”) while creating its instance.

var messageLogger = new MessageLogger(LogInFile);

You can also use “+=” while attaching first method to delegate instance in below manner.

MessageLogger messageLogger=null;

messageLogger += LogInFile;

When you want to use multicast delegate then for attaching first method you can use new keyword or “+=”.But from attaching second method you should  use += or use += with new keyword.will see this as we proceed in our blog.

There is one interview question asked. If in above example there is error in “LogInDB(string message)”,then method “LogInServer(string message)” will be called?

If code inside “LogInDB(string message)”  is properly handled using try catch then method “LogInServer(string message)” will be called else method “LogInServer(string message)” will not be called.

Now take another example of multicast delegate. Where delegate will be pointing to function having return type int.

Delegate1.2

When we call objcalc(5, 2);

Functions will get called in below order

AddNumber(int x,int y)

MultiplyNumber(int x, int y)

SubtractNumber(int x, int y)

But result of last function will be returned. Hence result of SubtractNumber(int x, int y) is returned which is 3.

If you want to call method sequentially then you can use method “GetInvocationList()”. As our delegate instance is pointing to three methods so, “GetInvocationList()” will return three delegate. Each delegate will be point to one method. In above image “arrdelegate.Length” will return three as it has three delegate.

 Publisher/Subscriber example

Now let’s take one more example of publisher/subscriber using multicast delegate.Let’s say we are having Application running. When there is error in Application we want to write error in file and database. For logging error in file and database we have created two classes. Also you can see in below image we have also created one delegate.

Delegate2

We have one class (LogInFile) which will write in File. We have one more class (LogInDB) which will write in database .See below image. Now when there is error in our application instance then, instance of  classes (LogInFile and LogInDB) should be notified so that they can do respective logging.

Delegate3

As you can see Logger delegate is pointing to multiple function or you can say multiple function has been attached to delegate with help of “+=”.So when Logger delegate is invoked it will call function in order in which they have been attached. So first Log method of LogInDB will called then Log method of LogInFile is get called. So if there is error in “DoProcessing” method of “MyApplication” then delegate Logger will be invoked and Log methods will be called. In above code I have tried to introduce error intentionally.

In above example publisher is “MyApplication” class(with help of delegate).Subscriber is “LogInFile” and “LogInDB” with help of their method Log(string message).

Now there is hack in above code. See below line.

myapp.Logger += logger2.Log;

After above line if somebody accidentally does myapp.Logger=null;

Then If there is any error in MyApplication.Then logging will not happen.

Also there is one more hack

myapp.Logger += logger2.Log;

After above line somebody accidentally does

myapp.Logger +=new MessageLogger( logger3.Log);

If there is any error in MyApplication.Then logging will happen only with logger3.Log method.

Note: We assume that we have created one more instance logger3, of some class “LogThroughEmail” which has Log function which is sending mail.

To overcome this type of situation we have introduce concept of Event.

 What is Event in c#? How it differ from delegate?

Event has higher level of abstraction as compare to delegate. It is declare as given below

event delegateName eventname

First parameter above is event keyword. Second parameter is name of delegate Third one is name of event. So we can say event is delegate type. When Event is raised it will call delegate (event handler) which will call function (handler) attached(subscribe) to it. So let’s rewrite above example with help of event.

We need to make small change in “Myapplication” class. Only one line is changed.we have just used event Logger.

Delegate4.png

In above example your handler (subscriber) signature should match with signature of Event’s delegate (MessageLogger) signature.When you are subscribing to event means you are indirectly attaching function to delegate of event.

Note: before declaring event you need to declare its delegate type. We had already declared “MessageLogger” delegate.

Below is same example but I have used traditional approach of subscribing event.

Delegate5

Difference between Event and delegate?

1> You can only raise event only from inside class/Struct. You cannot raise event from outside the class/struct. Event “Logger” can be only raised from inside class “MyApplication”. From outside “MyApplication” class we can only subscribe to event “Logger”, we cannot raise it. Delegate type can be invoked from inside and outside of the class/struct.

2>A delegate is a type that’s why we can access it from the class, but not from an instance.

delegate4.1

As you can see above we have declared delegate and event inside class and we are not able to access delegate at instance level. But we are able to access delegate at class level(using class name). In above example you will be not able to attach handler to delegate or invoked it while accessing it  using class name.

Now below we have declared class level variable of type delegate “MyHandler”.

delegate4.2

You can see that we are able to access “MyDelegate” at instance level.Also we are able to invoke delegate type (“MyDelegate”) from inside and outside class. So class/struct member of type delegate are accessible at instance level.

Now let’s throw some light on how to attach multiple handlers to event and delegate.

delegate4.3

You can see in above screenshot we have attached multiple handler to our event and delegate. For attaching second handler we have used +=.

delegate4.4

In Above example we have used “=” for attaching second handler hence only second handler is invoked. So if you are using, “=” to attach handler to event or delegate then if there are any  other handlers attach to event and delegate will not be invoked. So if you want to attach multiple handler, then you should use +=.

3> You can subscribe to event but cannot assign null(outside class).

We cannot do: myapp.Logger =null;//if Logger is event

If you assign null to event while subscribing it, then you will not able to compile program. You can assign null to delegate while subscribing them.

4> You can only declare event inside class. You can not declare event outside class. We can declare delegate inside and outside class as Delegate is type.

5>Interface can contain event but you cannot declare delegate inside interface.

If you are from Winform/wpf  or asp.net background then you should have used event lot. Below is sample form designed. We have two button Save and Delete.>

Let say name of Save button is “button1”. it’s text will be “Save”.

Delegate6

Now if you want to execute some code when Save button is clicked then you will just double click on “Save” button and automatically in code behind below code will be generated.

private void button1_Click(object sender, EventArgs e)

{

}

And below code in designer file is generated.

this.button1.Click += new System.EventHandler(this.button1_Click);

Whatever the code you will be writing inside above function (button1_Click), will be executed when Save button is clicked. But can you think in term of event.

You have Subscribe to click event of Button (click event is declare in class Control  which is base class of button).Click event is type of delegate EventHandler.

public delegate void EventHandler(object sender, EventArgs e);

 So your handler/Subscribe method ( “button1_Click”) has same signature as of delegate EventHandler.

So if someone clicks on Save button then click event is invoked from button class and you can take action on that by subscribing to click event. As we have explained above.

Kindly go through blog on ready made delegate Action,Predicate and Func

Published by

dotnetwithwindowandweb

I am dot net developer interested in web and windows technology.My major skill set are c#,multhithreading,linq,winform,wpf,WCF,Sql server and Angular

6 thoughts on “What are Delegate and Multicast delegate in C#? What are event and what is difference between delegate and event in c#?”

Leave a comment