We are providing online training of realtime Live project on Asp.Net MVC with Angular and Web API. For more information click here. If you have any query then drop the messase in CONTACT FORM

Sunday, June 28, 2015

What is Delegate in C# and Explain with Example?

A delegate is a type that represents references to methods with a particular parameter list and return type. A delegate (known as function pointer in C/C++) is a reference type that invokes single/multiple methods (s) through the delegate instance. It holds a reference to the methods. Whenever we want to create delegate methods we need to declare with delegate keyword.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.
  • 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.

What is the use of Delegates?
Suppose if we have multiple methods with the same signature (return type & a number of parameters) and want to call all the methods with a single object then we can go for delegates.

What is the difference between method overloading and delegate?
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.

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.

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 we to develop components that have a higher reusability factor.

What are the uses of delegates/callback functions?
1)to sort elements within an array.
2)callback functions are required for window procedures, hook procedures, asynchronous procedure calls.
3) to get assembly load/to 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.
4)Delegates are useful in situations where we need an intermediary between a calling procedure and the procedure being called.
5)We 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 we 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 we 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, we 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, we pass the custom sort procedure to the sort class at run time, using delegates.
6)The use of delegates promotes good separation of functionality between the database and the client code.

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.

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.

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

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.
In the .NET Framework class library, events are based on the EventHandler delegate and the EventArgs base class.

How will you subscribe to events?
Using event Handler
Define an event handler method whose signature matches the delegate signature for the event. For example, if the event is based on the EventHandler delegate type, the following code represents the method stub:

void HandleCustomEvent(object sender, CustomEventArgs a)

{ // Do something useful here. }

Use the addition assignment operator (+=) to attach your event handler to the event. In the following example, assume that an object named publisher has an event named RaiseCustomEvent. Note that the subscriber class needs a reference to the publisher class in order to subscribe to its events.
publisher.RaiseCustomEvent += HandleCustomEvent;

An event handler can also be added by using a lambda expression:
public Form1()
    {
        InitializeComponent();
        // Use a lambda expression to define an event handler.
        this.Click += (s, e) => {
            MessageBox.Show(((MouseEventArgs)e).Location.ToString());
        };

    }
To subscribe to events by using an anonymous method:
Use the addition assignment operator (+=) to attach your anonymous method to the event.
In the following example, assume that an object named publisher has an event named RaiseCustomEvent and that a CustomEventArgs class has also been defined to carry some kind of specialized event information. Note that the subscriber class needs a reference to publisher in order to subscribe to its events.
publisher.RaiseCustomEvent += delegate(object o, CustomEventArgs e)
{ string s = o.ToString() + " " + e.ToString();
Console.WriteLine(s);
};

How to unsubscribe from the event?
To prevent our event handler from being invoked when the event is raised, unsubscribe from the event. In order to prevent resource leaks, we should unsubscribe from events before we dispose of a subscriber object. Until we 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 our subscriber object.
To unsubscribe from an event
Use the subtraction assignment operator (-=) to unsubscribe from an event:
publisher.RaiseCustomEvent -= HandleCustomEvent;

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.

How will you handle Exceptions in multicast delegates?
Suppose 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. We 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, we 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 us to invoke each delegate within the try block of an exception handler.

Explain Anonymous Methods in Delegates?
Sometimes, we 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, we reduce the overhead in instantiating delegates by eliminating the need of separate method. Example:
AddDelegate add = delegate (int k) {return a + b;};

Explain Covariance and Contravariance in Delegates ?
These provide a degree of flexibility while matching delegate methods with delegate signatures.
Covariance: Covariance permits a method with a derived return type to be used as a delegate. When a delegate method has a return type that is derived from the return type of delegate, it is called a covariant. Because the return type of method is derived from the return type of delegate, the type conversion is implicit. This enables us to create delegate methods that can be used by the base and derived classes.

    public class BaseClass
    {
        // Some functions}
        public class DerivedClass : BaseClass
        { // Some functions}
            public class MainClass
            { // Define a delegate delegate BaseClass TestDelegate(); private static DerivedClass ReturnDerived()

{ return new DerivedClass();
            }
            public static void Main(string[] args)
            { // Covariance allows this TestDelegate delg = ReturnDerived; }}

            }

}

Contravariance:
Contravariance permits a method with derived parameters to be used as a delegate. When a delegate method signature has parameters that are derived from the delegate parameters, the method is said to be contravariant.


    public class BaseClass
    {
        // Some functions
    }
    public class DerivedClass : BaseClass
    {
        // Some functions
    }
    public class MainClass
        {
        // Define a delegate
        delegate BaseClass TestDelegate(BaseClass baseClassArg);
        private static DerivedClass ReturnDerived(DerivedClass dr)
        {
            return dr;
        }
        public static void Main(string[] args)
            {
            // Contravariance allows this
            TestDelegate delg = ReturnDerived;
        }
    }



What is the event Handler?
Event handlers are nothing more than methods that are invoked.

How do you declare delegates?
e.g:public delegate void ProcessBookDelegate(Book book);

How do you instantiate a delegate?
e.g:bookDB.ProcessPaperbackBooks(PrintTitle);

How do you call a delegate?
processBook(b);

Explain how delegates are used in asynchronous programming?
Delegates enable us to call a synchronous method in an asynchronous manner. When we 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.

Explain about BeginInvoke method of delegates?
The BeginInvoke method initiates the asynchronous call. It has the same parameters as the method that we 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. A 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.

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 we want to execute asynchronously, plus the IAsyncResult returned by BeginInvoke.

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

Explain about WaitHandle?
We can obtain a WaitHandle by using the AsyncWaitHandle()property of the IAsyncResult returned by BeginInvoke.The WaitHandle is signaled when the asynchronous call completes, and we can wait for it by calling the WaitOne()method.
If we use a WaitHandle, we 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 we call EndInvoke. If we 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 we 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 of.

How will you know when the asynchronous call completes?
use the IsCompleted() property of the IAsyncResult returned by BeginInvoke.

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.

What are the design patterns .Net provides to accomplish asynchronous operations?
The .NET Framework provides two design patterns for asynchronous operations:
Asynchronous operations that use IAsyncResult objects.
Asynchronous operations that use events.
The IAsyncResult design pattern allows for a variety of programming models but is more complex to learn and provides a flexibility that most applications do not require. Where possible, class library designers should implement asynchronous methods using the event-driven model.

Where Asynchronous programming feature supported in .Net?
Asynchronous programming is a feature supported by many areas of the .NET Framework, including:
File IO, Stream IO, Socket IO.
Networking.
Remoting channels (HTTP, TCP) and proxies.
XML Web services created using ASP.NET.
ASP.NET WebForms.
Message Queuing using the MessageQueue class.
Suppose in a scenario if we want to display information only until 4.00 p.m and after that means after 4.00 p.m if anyone tries to access the information it should give error messages. Then how will you write a delegate for this ? Give coding. 


   delegate void InformDelegate();
    class Program
    {
        static void Main(string[] args)
        {
            InformDelegate info = null;
            Display disp = new Display();
            if (DateTime.Now.Hour < 16)
            {
                info = new InformDelegate(disp.morning);
            }
            else
            {
                info = null;
            }
        }

        class Display
        {
            public void morning()
            {
                Console.WriteLine("display");
            }
            public void Evening()
            {
                Console.WriteLine("You are not allowed to access the information in this time. Try tomorrow morning");
            }
        }

No comments: