Saturday 26 March 2011

Delegates and events Interview Questions

What’s a delegate?

A delegate object encapsulates a reference to a method.

What are the different types of delegates?

Two types:

1. Unicast delegate: Delegate which is used to call a single method is called unicast delegate.
2. Multicast delegate: Delegate which is used to call a more than one method is called multicast delegate.


Do events have return type ?

No events do not have return type.

Can event’s have access modifiers ?

Event’s are always public as they are meant to serve every one registering to it.But we can use access modifiers in events. we can have events with protected keyword which will be accessible only to inherited classes. We can have private events only for object in that class.

Can we have shared events ?

Yes we can have shared event’s note only shared methods can raise shared events.

What’s difference between delegate and events?

1. Actually events use delegates in bottom. But they add an extra layer on the delegates, thus forming the publisher and subscriber model.
2. 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 pretty confusing. But events give the extra protection by adding the layer and making it a publisher and subscriber model.

What is an Asynchronous delegate?

Delegates used to invoke method that takes long time to execute.

How to create events for a control? What are custom events?


Declare a public delegate and set of events to listen from.
public delegate void CarEventHandler(string msg);
public event CarEventHandler AboutToBlow;
public event CarEventHandler BlewUp

Steps to use delegate?

1. Create delegate: delegate returntype nameofdelegate(parameter passed to method);
2. Create instance of delegate: delname objname = new delname(classobj.nameofmethod);
3. Invoke delegate: datatype parameter of method = objname("value to pass ");

What is invocationlist?

Multicast delegate contains internal lis tof delegate. This list is called invocationlist.

** += and -= operators are use dto add and remove delegates from invocationlist.

No comments:

Post a Comment