Delegates & Events



1. What is delegate?  

Delegates are objects you can use to call the methods of other objects.

A delegate is a type that safely encapsulates a method, similar to a function pointer in C and C++. Unlike C function pointers, delegates are object-oriented, type safe, and secure. The type of a delegate is defined by the name of the delegate.

Once a delegate is assigned a method, it behaves exactly like that method.

The delegate method can be invoked like any other method, with parameters and a return value.

Any method from any accessible class or struct that matches the delegate's signature, which consists of the return type and parameters, can be assigned to the delegate.

The method can be either static or an instance method. This makes it possible to programmatically change method calls, and also plug new code into existing classes. As long as you know the signature of the delegate, you can assign your own delegated method.

Delegates have the following properties:
Delegates are like C++ function pointers but are type safe.
Delegates allow methods to be passed as parameters.
Delegates can be used to define callback methods.
Delegates can be chained together; for example, multiple methods can be called on a single event.
Methods do not have to match the delegate signature exactly.



2. What is the difference between method overloading and delagate?  

In the context of method overloading, the signature of a method does not include the return value. But in the context of delegates, the signature does include the return value.



3. Why callback methods use delegates?  

This ability to refer to a method as a parameter makes delegates ideal for defining callback methods. For example, a sort algorithm could be passed a reference to the method that compares two objects. Separating the comparison code allows for the algorithm to be written in a more general way.



4. What is the importance of delegates and events in designing large applications?  

The use of delegates and events in the design of a large application can reduce dependenciesand the coupling of layers.This allows you to develop components that have a higher reusability factor.




5. What are the uses of delegates/callback functions?  

  • To sort elements within an array.
  • Callback functions are required for window procedures, hook procedures, asynchronous procedure calls.
  • To get assembly load/unload notifications, unhandled exception notifications, database/window state change notifications, file system change notifications, menu item selections, completed asynchronous operation notifications, filtering a set of items, and so on.
  • Delegates are useful in situations where you need an intermediary between a calling procedure and the procedure being called.
  • You can use delegates for other, non-event related tasks, such as free threading or with procedures that need to call different versions of functions at compile time.
  • e.g:suppose you have a classified-ad application that includes a list box with the names of cars. The ads are sorted by title, which is normally the make of the car. A problem you may face occurs when some cars include the year of the car before the make. The problem is that the built-in sort functionality of the list box sorts only by character codes; it places all the ads starting with dates first, followed by the ads starting with the make.
    To fix this, you can create a sort procedure in a class that uses the standard alphabetic sort on most list boxes, but is able to switch at run time to the custom sort procedure for car ads. To do this, you pass the custom sort procedure to the sort class at run time, using delegates.
  • The use of delegates promotes good separation of functionality between the database and the client code.


6. What is Delegate invocation?  

A delegate object is normally constructed by providing the name of the method the delegate will wrap, or with an anonymous Method. Once a delegate is instantiated, a method call made to the delegate will be passed by the delegate to that method. The parameters passed to the delegate by the caller are passed to the method, and the return value, if any, from the method is returned to the caller by the delegate. This is known as invoking the delegate.



7. What is asynchronous callback ?  

Delegate types are sealed—they cannot be derived from— and it is not possible to derive custom classes from Delegate. Because the instantiated delegate is an object, it can be passed as a parameter, or assigned to a property. This allows a method to accept a delegate as a parameter, and call the delegate at some later time. This is known as an asynchronous callback, and is a common method of notifying a caller when a long process has completed. When a delegate is used in this fashion, the code using the delegate does not need any knowledge of the implementation of the method being used. The functionality is similar to the encapsulation interfaces provide.



8. When to Use Delegates Instead of Interfaces?  

Both delegates and interfaces enable a class designer to separate type declarations and implementation. A given interface can be inherited and implemented by any class or struct. A delegate can be created for a method on any class, as long as the method fits the method signature for the delegate. An interface reference or a delegate can be used by an object that has no knowledge of the class that implements the interface or delegate method. Given these similarities, when should a class designer use a delegate and when should it use an interface?
Use a delegate in the following circumstances:
An eventing design pattern is used.
It is desirable to encapsulate a static method.
The caller has no need to access other properties, methods, or interfaces on the object implementing the method.
Easy composition is desired.
A class may need more than one implementation of the method.
Use an interface in the following circumstances:
There is a group of related methods that may be called.
A class only needs one implementation of the method.
The class using the interface will want to cast that interface to other interface or class types.
The method being implemented is linked to the type or identity of the class: for example, comparison methods.



9. What is Multicast delegate?  

Multicast delegates can be defined as delegates that have more than one element in their invocation list. In other words, it is a delegate that is subscribed by more than one method.

A MulticastDelegate has a linked list of delegates, called an invocation list, consisting of one or more elements. When a multicast delegate is invoked, the delegates in the invocation list are called synchronously in the order in which they appear. If an error occurs during execution of the list then an exception is thrown.



10. How will you handle Exceptions in multicast delegates?  

Suppose you have added multiple delegates to a single multicast delegate. Each of these individual delegates must be invoked, regardless of whether an unhandled exception is thrown within one of the delegates. But, once a delegate in a multicast delegate throws an unhandled exception, no more delegates are fired. You need a way to trap unhandled exceptions within each individual delegate while still allowing the rest of the delegates to fire.
To avoid breaking the chain, you have to gracefully handle exceptions in all functions. Use the GetInvocationList method. This method returns each individual delegate from a multicast delegate and, by doing so, allows you to invoke each delegate within the try block of an exception handler.

Expain Anonymous Methods in Delegates?

Sometimes, you want to use a very small amount of code to call a delegate. Creating functions for such a small code will make the code cumbersome and difficult to read and debug. C# 2.0 comes with a new concept of Anonymous methods. By using anonymous methods, you reduce the overhead in instantiating delegates by eliminating the need of separate method. Here is the small example to illustrate this./************************************************************/
AddDelegate add = delegate (int k) {return a + b;};
/************************************************************/



11. How do you declare delegates?  

public delegate void ProcessBookDelegate(Book book);


12. How do you instantiate a delegate?  

bookDB.ProcessPaperbackBooks(PrintTitle);


13. How do you call a delegate?  

processBook(b);


14. Explain how delegates are used in asynchronous programming?  

Delegates enable you to call a synchronous method in an asynchronous manner. When you call a delegate synchronously, the Invoke method calls the target method directly on the current thread. If the BeginInvoke method is called, the common language runtime (CLR) queues the request and returns immediately to the caller. The target method is called asynchronously on a thread from the thread pool. The original thread, which submitted the request, is free to continue executing in parallel with the target method. If a callback method has been specified in the call to the BeginInvoke method, the callback method is called when the target method ends. In the callback method, the EndInvoke method obtains the return value and any input/output or output-only parameters. If no callback method is specified when calling BeginInvoke, EndInvoke can be called from the thread that called BeginInvoke.

Note:Compilers should emit delegate classes with Invoke, BeginInvoke, and EndInvoke methods using the delegate signature specified by the user. The BeginInvoke and EndInvoke methods should be decorated as native. Because these methods are marked as native, the CLR automatically provides the implementation at class load time. The loader ensures that they are not overridden.



15. Expain about BeginInvoke method of delegates?  

The BeginInvoke method initiates the asynchronous call. It has the same parameters as the method that you want to execute asynchronously, plus two additional optional parameters. The first parameter is an AsyncCallback delegate that references a method to be called when the asynchronous call completes. The second parameter is a user-defined object that passes information into the callback method. BeginInvoke returns immediately and does not wait for the asynchronous call to complete. BeginInvoke returns an IAsyncResult, which can be used to monitor the progress of the asynchronous call.



16. Expain about EndInvoke method?  

The EndInvoke method retrieves the results of the asynchronous call. It can be called any time after BeginInvoke. If the asynchronous call has not completed, EndInvoke blocks the calling thread until it completes. The parameters of EndInvoke include the out and ref parameters

of the method that you want to execute asynchronously, plus the IAsyncResult returned by BeginInvoke.



17. How to obtain Waithandle ?  

You can obtain a WaitHandle by using the AsyncWaitHandle()property of the IAsyncResult returned by BeginInvoke.



18. Explain about WaitHandle?  

You can obtain a WaitHandle by using the AsyncWaitHandle()property of the IAsyncResult returned by BeginInvoke.TheWaitHandle is signaled when the asynchronous call completes, and you can wait for it by calling the WaitOne()method.

If you use a WaitHandle, you can perform additional processing before or after the asynchronous call completes, but before calling EndInvoke to retrieve the results.

Note:The wait handle is not closed automatically when you call EndInvoke. If you release all references to the wait handle, system resources are freed when garbage collection reclaims the wait handle. To free the system resources as soon as you are finished using the wait handle, dispose of it by calling the WaitHandleClose()method. Garbage collection works more efficiently when disposable objects are explicitly disposed.



19. How will you know when the asynchronous call completes?  

use the IsCompleted() property of the IAsyncResult returned by BeginInvoke .



20. When Asynchronous operations are used?  

Asynchronous operations are typically used to perform tasks that might take a long time to complete, such as opening large files, connecting to remote computers, or querying a database. An asynchronous operation executes in a thread separate from the main application thread. When an application calls methods to perform an operation asynchronously, the application can continue executing while the asynchronous method performs its task.



Java Interview Question

.Net Interview Question

PHP Interview Question

AngularJS Interview Questions