EventHandler

In this chapter you will learn:

  1. How to use EventHandler in C#

Using EventHandler

using System; /*from   j  a  v  a2 s  .c  o  m*/
 
// Declare an event class. 
class MyEvent { 
  public event EventHandler SomeEvent; // uses EventHandler delegate 
 
  // This is called to fire SomeEvent. 
  public void OnSomeEvent() { 
    if(SomeEvent != null) 
      SomeEvent(this, EventArgs.Empty); 
  } 
} 
 
public class EventDemo6 { 
  static void handler(object source, EventArgs arg) { 
    Console.WriteLine("Event occurred"); 
    Console.WriteLine("Source is " + source); 
  } 
 
  public static void Main() {  
    MyEvent evt = new MyEvent(); 
 
    // Add handler() to the event list. 
    evt.SomeEvent += new EventHandler(handler); 
 
    // Fire the event. 
    evt.OnSomeEvent(); 
  } 
}

Next chapter...

What you will learn in the next chapter:

  1. Get to know C# standard event pattern
  2. Example to use event pattern
Home » C# Tutorial » delegate, lambda, event
delegate
Multicast delegate
delegate variables
delegate parameters
Generic delegate
delegate return
Func and Action
delegate new
chained delegate
Anonymous delegate
delegate array
Return a delegate
delegate as parameter
Event
event multicast
static event
EventHandler
Event pattern
lambda
lambda syntax
Func, Action and lambda
lambda with outer function
lambda iteration variables