Saturday, 15 March 2014

Interview Questions and Answers Of Delegates and Events in C#

Delegates

1.What is a Delegate ?

  A delegate is a class  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.

2.What are the types of  delegate?

            1.Single cast delegate:
                        It is used to  hold the reference of one method only.
            Syntax:
            <accessspecifier> delegate <returntype> delegate_name;

            2.Multicast Delegate:
                        It is used to hold the reference of more than one method.
               Example:



mc.MyDelegate += new MyDelegate( mc.Method1 );
mc.MyDelegate += new MyDelegate( mc.Method2 );
mc.MyDelegate = mc.MyDelegate + new MyDelegate( mc.Method3 );




3.Explain 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.

Example:  add = delegate (int k) {return a + b;};

4.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.

Example:    public void sum(int a,int b)
                   public void sum(int a,int b,int c);
                    
                  public delegate int mydelegate(int a,int b);

5.Why callback methods use delegates?

            This ability to refer to a method as a parameter makes delegates ideal for defining callback methods.

Example:
            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.

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.Explain 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.

8.Explain 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.

9.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.

10. 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.

11. 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.

  1. What is the main use of delegates in C#?
           Delegates are mainly used to define call back methods.

12.Can we other than void return type in multicast delegate ? 

            No it will cause Exceptions

13.Can I convert single cast delegate to multicast delegate ?

14.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
dependencies and the coupling of layers. This allows you to develop components that
have a higher reusability factor.

15.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.
            A class may need more than one implementation of the method.

16.What is generic delegate?
            A delegate can define its own type parameters.

17.In which area delegates are commonly used?
            Multithreading ,event handling.


Events

18.What are Events?

Events enable a class or object to notify other classes or objects when something of interest occurs. The class that sends (or raises) the event is called the publisher and the classes that receive (or handle) the event are called subscribers.

Events have the following properties:

The publisher determines when an event is raised;.
The subscribers determine what action is taken in response to the event.
An event can have multiple subscribers. A subscriber can handle multiple events from multiple publishers.
Events that have no subscribers are never called.
Events are typically used to signal user actions such as button clicks or menu selections in graphical user interfaces.
When an event has multiple subscribers, the event handlers are invoked synchronously when an event is raised.
Events can be used to synchronize threads.

19.How will you subscribe to events?

Use the addition assignment operator (+=) to attach your event handler to the event.

20. How to unsubscribe from event?

To prevent your event handler from being invoked when the event is raised, unsubscribe from the event. In order to prevent resource leaks, you should unsubscribe from events before you dispose of a subscriber object. Until you unsubscribe from an event, the multicast delegate that underlies the event in the publishing object has a reference to the delegate that encapsulates the subscriber's event handler. As long as the publishing object holds that reference, garbage collection will not delete your subscriber object.

To unsubscribe from an event

                    Use the subtraction assignment operator (-=) to unsubscribe from an event:
                     publisher.RaiseCustomEvent -= HandleCustomEvent;

21.What is event Handler?

It is a non value returning method.

22.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 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.

23.do events have any return type?

        No,because they have to serve multiple users.

24.Can event have access modifiers?

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

25.Can we have shared events ?

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

26.what is difference between events & delegates?

Event:

1) It is a data member of a type(class/structure)
2)It is declared inside a type(class/structure)
3) It is used to generate notifications which are then passed to methods though
Delegate:

1)It is a datatype(reference type) that holds references of methods with some signatures also                  called as function pointer.
2)It may or may not be declared inside a class.
3)It is used as the return type of an event and used in passing messages from event to                              methods.

27.Rules to fallow while declaring delegates?

            1.No of arguments in delegate's and in method should be same.
            2.Return type of method and delegate should be same.

28.Explain about WaitHandle?

     You can obtain a WaitHandle by using the AsyncWaitHandle()property of the IAsyncResult
returned by Begin Invoke.
   The WaitHandle 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 End Invoke to retrieve the results.

29.How to obtain Wait handle ?

  You can obtain a Wait Handle by using the A syncWait Handle()property of the IAsyncResult returned by Begin Invoke.

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

  Use the Is Completed() property of the IAsyncResult returned by Begin Invoke .




No comments:

Post a Comment