Delegate in c#

Delegate in c#

What is delegate in c#??

In this lesson we learn delegate.We know that structure are value type but classes and interfaces are reference type .Similarly Delgate is reference type.

  1. A delegate is a funtion pointer.
  2. A delegate is type safety
  3. A delegate can be used to define callback methods.

Let us understand with Example.

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    public delegate void Hellofunctiondelegate(string message);
    class Delegate
    {
        static void Main(string[] args)
        {
            //a delegate is a type safety function pointer
            Hellofunctiondelegate del = new Hellofunctiondelegate(Hello);
            del("hello world delegate");
        }
        public static void Hello(string strmessage)
        {
            Console.WriteLine(strmessage);
        }
    }
}

What is multicast Delegate??

Let us understand A multicast delegate is a delegate that has reference to more than one function. When you invoke a multicast delegate,all the function the delegate is pointing to,are invoked

There are two approaches to create a multicast delegate.Depending on the approach you use
 + or+= to register method with the delegate
-or-= to un-register a method with the delegate.

Note: A multicast delegate,invokes the methods in the invocation list,in the same order in which they are added.
If the delegate has a return type other than void and if the delegate is a multicast delegate
This means only the value of the last invoked method will be returned.Along the same lines,If the delegates has an out parameter,the value of the output parameter, will be the value assigned by the last method.

Then you put where do you use multicast delegate??

Multicast delegate makes implementation of observer design pattern very simple.Observer pattern is also as publish/subscribe pattern.


Let's Scenarios we can use Multicast Delegate

Let's understand Error Handling through Event log, E Mail, File, Mobile Methods can done through Multicast Delegate where publisher has a Multicast Delegate which has reference to all methods.

Post a Comment

0 Comments