Events:Add and Remove Functions : delegate Event « Language Basics « C# / C Sharp





Events:Add and Remove Functions

Events:Add and Remove Functions
using System;

public class AddandRemoveFunctions {
    static public void ButtonHandler(object sender, EventArgs e)
    {
        Console.WriteLine("Button clicked");
    }
    
    public static void Main()
    {
        Button button = new Button();
        
        button.AddClick(new Button.ClickHandler(ButtonHandler));
        
        button.SimulateClick();
        
        button.RemoveClick(new Button.ClickHandler(ButtonHandler));
    }
}
public class Button
{
    public delegate void ClickHandler(object sender, EventArgs e);
    private ClickHandler click;
    
    public void AddClick(ClickHandler clickHandler)
    {
        click += clickHandler;
    }
    
    public void RemoveClick(ClickHandler clickHandler)
    {
        click -= clickHandler;
    }
    
    protected void OnClick()
    {
        if (click != null)
        click(this, null);
        
    }
    
    public void SimulateClick()
    {
        OnClick();
    }
}

           
       










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 Functions 2Events:Add and Remove Functions 2
10.Events: Custom Add and RemoveEvents: Custom Add and Remove
11.Delegates And EventsDelegates And Events
12.Delegates And Events 2Delegates And Events 2
13.Chaining events.