Mega Code Archive

 
Categories / C# Book / 01 Language Basics
 

0191 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; 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 = "rntsoft.com"; } } The output: console handler:rntsoft.com event can have the following modifiers. virtual overridden abstract sealed static