Following are various .NET interview questions asked by the interviewer.
Events are higher level of encapsulation over delegates. Events use delegates internally. Delegates are naked and when passed to any other code, the client code can invoke the delegate. Event provides a publisher / subscriber mechanism model.
So subscribers subscribe to the event and publisher then push messages to all the subscribers. Below is a simple code snippet for the same:-
Create a delegate and declare the event for the same.
public delegate void CallEveryone(); public event CallEveryone MyEvent;
Raise the event.
Attached client methods to the event are fired / notified.
obj.MyEvent += Function1;
Difference between delegate and events: -
They cannot be compared because one derives from the other.
- Actually, events use delegates in bottom. But they add an extra layer of security on the delegates, thus forming the publisher and subscriber model.
- As delegates are function to pointers, they can move across any clients. So any of the clients can add or remove events, which can be confusing. But events give the extra protection / encapsulation by adding the layer and making it a publisher and subscriber model.
Just imagine one of your clients doing this
c.XyzCallback = null
This will reset all your delegates to nothing and you have to keep searching where the error is.