A very simple event demonstration : delegate Event « Language Basics « C# / C Sharp






A very simple event demonstration

A very simple event demonstration
/*
C#: The Complete Reference 
by Herbert Schildt 

Publisher: Osborne/McGraw-Hill (March 8, 2002)
ISBN: 0072134852
*/


// A very simple event demonstration. 
  
using System; 
 
// Declare a delegate for an event.  
delegate void MyEventHandler(); 
 
// Declare an event class. 
class MyEvent { 
  public event MyEventHandler SomeEvent; 
 
  // This is called to fire the event. 
  public void OnSomeEvent() { 
    if(SomeEvent != null) 
      SomeEvent(); 
  } 
} 
 
public class EventDemo { 
  // An event handler. 
  static void handler() { 
    Console.WriteLine("Event occurred"); 
  } 
 
  public static void Main() {  
    MyEvent evt = new MyEvent(); 
 
    // Add handler() to the event list. 
    evt.SomeEvent += new MyEventHandler(handler); 
 
    // Fire the event. 
    evt.OnSomeEvent(); 
  } 
} 



           
       








Related examples in the same category

1.An event multicast demonstrationAn event multicast demonstration
2.Individual objects receive notifications when instance event handlers are usedIndividual objects receive notifications when instance 
   event handlers are used
3.A class receives the notification when a static method is used as an event handlerA class receives the notification when  
   a static method is used as an event handler
4.Create a custom means of managing the event invocation listCreate a custom means of managing the event invocation list
5.Use the bult-in EventHandler delegateUse the bult-in EventHandler delegate
6.Use delegate: eventUse delegate: event
7.Delegate and event hierarchyDelegate and event hierarchy
8.Events:Add and Remove FunctionsEvents:Add and Remove Functions
9.Events:Add and Remove Functions 2Events:Add and Remove Functions 2
10.Events: Custom Add and RemoveEvents: Custom Add and Remove
11.Delegates And EventsDelegates And Events
12.Delegates And Events 2Delegates And Events 2
13.Chaining events.