Event
In this chapter you will learn:
Event and delegate
C# formalizes the event handling by using delegate
.
It uses event
keyword to declare a
delegate
type as the event
listener and all delegate instances as the handler.
The following code defines a delegate as the
prototype for all event handlers.
delegate void PrinterEventHandler(string s);
It requires that all event handlers for the print events should take string as parameter.
The following code uses event keyword
to make a delegate
as an event
.
using System;/*from j av a2 s . c o m*/
public delegate void PrinterEventHandler(string s);
public class Printer
{
private string stringValue;
public event PrinterEventHandler printEventHandler;
public string StringValue
{
get
{
return stringValue;
}
set
{
printEventHandler(value);
stringValue = value;
}
}
}
class Test
{
static void consoleHandler(string str)
{
Console.WriteLine("console handler:" + str);
}
static void Main()
{
Printer p = new Printer();
p.printEventHandler += consoleHandler;
p.StringValue = "java2s.com";
}
}
The output:
event can have the following modifiers.
- virtual
- overridden
- abstract
- sealed
- static
Example for creating event
using System; /* j ava 2s . c o m*/
// 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();
}
}
Next chapter...
What you will learn in the next chapter:
Home » C# Tutorial » delegate, lambda, event