Home > DeveloperSection > Articles > Delegate and Event in C#

Delegate and Event in C#


C# C# 
Ratings:
5 Comment(s)
 4174  View(s)
Rate this:

Delegate and Event in C#

Delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked. Delegate is type-safe object which can point to method or multiple methods (Multicasting) of application. To define delegate we use keyword ‘Delegate’.

Let’s see an example on ‘Delegate and Event in C#’.

Example:

namespace delegateAndEvent

{

    public delegate void TimeEventHandler(string s); //declare a delegate

    public class Mytime

    {

        public event TimeEventHandler Timer; //declare a event

        public void OnTimer(string s)

        {

            if (null!=Timer)

            {

                Timer(s);  //raise the event

            }

        }

    }

    public class ProcessTime

    {

        public void GenerateTime(string s)   //event handle

        {

            Console.WriteLine("Hello {0}!The time is {1} now",s,DateTime.Now);

        }

    }

    class Program

    {

        static void Main(string[] args)

        {

            ProcessTime p = new ProcessTime();

            Mytime t = new Mytime();

            t.Timer += new TimeEventHandler(p.GenerateTime);//To link events and event handling

            t.OnTimer("Mindstick");   //use event

        }

    }

}

 

 

Note: While defining delegate we need to keep in mind that return type, arguments should be same as the return type and arguments of methods to which it is going to point to.


Delegate and event in c#.

By Jenry Hock on   5 years ago
Hi Aken,
Good one, You had understand concept of event delegate.
I have one suggesstion to you. If you will explain code and terms of your article then that is more usefull for users or learners.

Thanks,

Delegate and event in c#.

By aken H on   5 years ago

Hi Jenry, Thanks.

  


Delegate and event in c#.

By Pooja Malohtra on   5 years ago
can you provide more articles on the same concept?

delegate and event

By aken H on   5 years ago
hi Sanjay Singh,
    you can find the latest articles in click "article".
hope the can help you.
good luck!

Events With Delegate

By Sanjay Singh on   4 years ago
Hi Pooja and Aken !

I have added a article on Events and delegates .
Tell me how do u find it?


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

Follow MindStick