Chaining events. : delegate Event « Language Basics « C# / C Sharp






Chaining events.

 


using System;

public class EventTestClass {
    private int nValue;
    public delegate void ValueChangedEventHandler();
    public event ValueChangedEventHandler Changed;
    protected virtual void OnChanged() {
        if (Changed != null)
            Changed();
        else
            Console.WriteLine("Event fired. No handler!");
    }

    public EventTestClass(int nValue) {
        SetValue(nValue);
    }
    public void SetValue(int nV) {
        if (nValue != nV) {
            nValue = nV;
            OnChanged();
        }
    }
}

public class Mainclass {
    public void HandleChange1() {
        Console.WriteLine("Handler 1 Called");
    }
    public void HandleChange2() {
        Console.WriteLine("Handler 2 Called");
    }
    public Mainclass() {
    }

    public static void Main() {
        EventTestClass etc = new EventTestClass(3);
        Mainclass app = new Mainclass();

        etc.Changed += new EventTestClass.ValueChangedEventHandler(app.HandleChange1);
        etc.Changed += new EventTestClass.ValueChangedEventHandler(app.HandleChange2);

        etc.SetValue(5);
        etc.SetValue(5);
        etc.SetValue(3);
    }
}

 








Related examples in the same category

1.A very simple event demonstrationA very simple event demonstration
2.An event multicast demonstrationAn event multicast demonstration
3.Individual objects receive notifications when instance event handlers are usedIndividual objects receive notifications when instance 
   event handlers are used
4.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
5.Create a custom means of managing the event invocation listCreate a custom means of managing the event invocation list
6.Use the bult-in EventHandler delegateUse the bult-in EventHandler delegate
7.Use delegate: eventUse delegate: event
8.Delegate and event hierarchyDelegate and event hierarchy
9.Events:Add and Remove FunctionsEvents:Add and Remove Functions
10.Events:Add and Remove Functions 2Events:Add and Remove Functions 2
11.Events: Custom Add and RemoveEvents: Custom Add and Remove
12.Delegates And EventsDelegates And Events
13.Delegates And Events 2Delegates And Events 2