Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Events and Methods

Tags:

methods

c#

events

I have some confusion regarding Events. What are the basic differences between C# Events and Methods?

like image 495
Shashank Avatar asked Feb 03 '12 10:02

Shashank


2 Answers

A method is simply code contained within a class to implement a piece of functionality. All code in C# is contained within methods.

As for events, well, suppose you had a simple class which implemented a counter (lets call it the Counter object). Now suppose you wanted to let other objects unrelated to Counter know when the count reached 100. How would you do it?

A logical way would be to allow the other objects to specify one of their own methods they want to be called when the count reaches 100. Each object could then, individually, tell the Counter object which method they want to be called. The Counter object saves this list of methods and, when the count reaches 100, calls each of the saved methods in turn.

This is the how Events work - the Counter class contains an event member (called say, CounterIs100) which other object instances link one of their own methods to. When the Counter object detects that it has has reached 100, it invokes the CounterIs100 member which, automatically, calls all the methods currently linked to it, thus notifying each object in turn that the count has indeed reached 100. If no objects have linked a method to the CounterIs100 event member, it will be null, so there is no need for the Counter object to invoke the event member.

class Counter
{
   // this is the count field used to save the current count value
   private int count;

   // this is the event member which holds all the methods other objects have specified
   public event CounterIs100Delegate CounterIs100;

   // This is a method. It invokes the CounterIs100 event member if anyone has subscribed to it
   protected void OnCounterIs100()
   {
       // see if anyone has subscribed (linked) their method to this event
       if (CounterIs100 != null)
       {
          // invoke the event - this will call all subscribed methods
          CounterIs100();
       }
   }

   // This is a method. It increments the counter variable stored by this object
   public void Increment()
   {
      count++;
      // if the count is 100, invoke the event
      if (count == 100)
         OnCounterIs100();
   }

}

// This is a delegate. It is used to define a template for other objects wishing to
// subscribe to the CounterIs100 event. The methods other objects link to the
// CounterIs100 event must match this declaration (although the name can be changed)
public delegate void CounterIs100Delegate();

// This is a class, unrelated to Counter, but uses its events
class SiteHits
{
     Counter hitCounter = new Counter();

     public SiteHits()
     {
         // We want to know when the number of site hits reaches 100.
         // We could monitor this ourselves, but we know the Counter class already
         // does this, so we just link our method to its event
         hitCounter.CounterIs100 += this.WhenSiteHitsReaches100;
     }

     public void PageRequested()
     {
         // someone has requested a page - increment the hit counter
         Console.WriteLine("We've been hit!");
         hitCounter.Increment();            
     }

     // this is the method we want called when the CounterIs100 event occurs.
     // note that the return value and parameters match CounterIs100Delegate above.
     public void WhenSiteHitsReaches100()
     {
         Console.WriteLine("Woohoo! We've reached 100 hits!");
     }
}
like image 200
adelphus Avatar answered Sep 23 '22 16:09

adelphus


C# Events are a specific form of delegates. If you have programmed in other languages, like C++, you could compare a delegate to a function ("method") pointer - it points to some code in memory. When you call the pointer as a method, you actually call the method at the address the pointer points to.

This is necessary to provide decoupling between the caller and the callee - so you don't have to have all methods ready when you publish code that calls them (which, wouldn't be possible - the Forms controls developers can't possibly know the code that needs to be called when a Button is pressed). You call the pointer, and the other developer sets it to an appropriate memory address later.

P.S. delegates and Events however, have other advantages over plain function pointers - you can be sure that it will point to a good-looking method, taking the correct number and type of arguments and returning the correct type.

like image 41
Vladislav Zorov Avatar answered Sep 22 '22 16:09

Vladislav Zorov