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 = "java2s.com";

    }
}

The output:


console handler:java2s.com

event can have the following modifiers.

java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.