3
Reply

what is diffrence between delegate and Event in C#?

    Delegate

    Delegate is a type which holds the method(s) reference in an object. It is also referred to as a type safe function pointer. Basically a delegate dynamically wires up a method caller to its target method.

    A delegate type declaration is preceded by the keyword delegate

    delegate int Transformer (int x);

    To create a delegate instance, you can assign a method to a delegate variable:

    class Test

    {

    static void Main()

    {

    Transformer t = Square; // Create delegate instance

    int result = t(3); // Invoke delegate

    Console.WriteLine (result); // 9

    }

    static int Square (int x) { return x * x; }

    }

     

    Event

    An event is a construct that exposes just the subset of delegate features required for the broadcaster/subscriber model. The main purpose of events is to prevent subscribers from interfering with each other. The broadcaster is a type that contains a delegate field. The subscribers are the method target recipients

    public class Broadcaster

    {

    public event ProgressReporter Progress;

    }

    Delegate is used to invoke Events.We can say,Delegate is a reference type variable or it changes the reference to a method at runtime whereas method is activated at the occurrence of an event where an event is associated with the delegate to call the method at runtime.Delegates are primarily used in C# programming for implementing events and callback methods.


    Program to understand the difference between Delegate and Events

    using System;
    class A
    {
    public delegate void MyDelegate(string argValue);
    public static void delegateFunction(string passvalue)
    {
    Console.WriteLine("{0} Console",passvalue);
    }
    public static void UseMethod()
    {
    MyDelegate dl=new MyDelegate(delegateFunction);
    DisplayData(dl);
    }
    public static void DisplayData(MyDelegate md)
    {
    md("This should go to the ");
    }
    public static void Main()
    {
    UseMethod();
    }

    }



    Delegates are actually Function Pointers in C++.Delegates are classes that can hold function or methods.Delegates have a signature and only those reference that can meet with the sigatures can be included with in the class.

       Syntax: delegate type delegatename (function name() );

    Event is an action performed on another part of the program.We can use delegate to raise an event.By default return type of an event is public.