Home > DeveloperSection > Articles > Event Delegate in C#

Event Delegate in C#


.NET .NET 
Ratings:
0 Comment(s)
 1433  View(s)
Rate this:

Event Delegate in C#

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

{

    public delegate void  ADelegate(int a);

    partial class Operation

    {

 

        public void Square(int a)

        {

         Console.WriteLine(a*a);

        }

       

    }

 

    class Program

    {

        static void Main(string[] args)

        {

            Operation obj = new Operation();

            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

{

    public delegate void  ADelegate(int a);

    partial class Operation

    {

 

        public void Square(int a)

        {

         Console.WriteLine(a*a);

        }

        public void Add(int a)

        {

            Console.WriteLine(a + 10);

        }

    }

 

    class Program

    {

        static void Main(string[] args)

        {

            Operation obj = new Operation();

            ADelegate objDele ;

           objDele = obj.Square;

            objDele += obj.Add;

              objDele(10);

             objDele(20);

 

        }

    }

}

 


Don't want to miss updates? Please click the below button!

Follow MindStick