articles

Event Delegate in C#

priyanka kushwaha5231 24-Jan-2015

In this blog, I’m explaining about the event and delegate in C#.

Definition of Delegate

A delegate is a type safe “function pointers”   that defines a method signature when you instantiate a delegate.

Syntax: 

Delegate <return type> DelegateType (arg type,arg type)

    Object

    Delegate

   Multicast Delegate

   Event Handler

Types of Delegate

1.      Single Delegate

2.      Multicast Delegate

Single Delegate

   Single delegate can be used to invoke  single method.

Example

namespace DelegateProgram
{
    publicdelegatevoid  ADelegate(int a);
    partialclassOperation
    {
 
        publicvoid Square(int a)
        {
         Console.WriteLine(a*a);
        }
       
    }
 
    classProgram
    {
        staticvoid Main(string[] args)
        {
            Operation obj = newOperation();
            ADelegate objDele ;
           objDele = obj.Square;
           
             objDele(20);
            Console.ReadLine();
 
        }
    }
}

 

Multi Delegate

  Multicast delegate can be used to invoke the multi method. Multicast Delegate use   + operator and – operator for invoke.

Example

namespace DelegateProgram
{
    publicdelegatevoid  ADelegate(int a);
    partialclassOperation
    {
 
        publicvoid Square(int a)
        {
         Console.WriteLine(a*a);
        }
        publicvoid Add(int a)
        {
            Console.WriteLine(a + 10);
        }
    }
 
    classProgram
    {
        staticvoid Main(string[] args)
        {
            Operation obj = newOperation();
            ADelegate objDele ;
           objDele = obj.Square;
            objDele += obj.Add;
              objDele(10);
             objDele(20);
 
        }
    }
}

 


Updated 24-Mar-2018

Leave Comment

Comments

Liked By