Skip to main content

Events and Delegates simplified


Introduction
An event is a message sent by an object to signal the occurrence of an action. The action could be caused by user interaction, such as a mouse click, or it could be triggered by some other program logic. The object that raises the event is called the event sender. The object that captures the event and responds to it is called the event receiver.

In event communication, the event sender class does not know which object or method will receive the events it raises. What is needed is an intermediary between the source and the receiver. The .NET Framework defines a special type that provides the functionality of a function pointer.

A delegate is a class that can hold a reference to a method. Unlike other classes, a delegate class has a signature, and it can hold references only to methods that match its signature. A delegate is thus equivalent to a type-safe function pointer or a callback. While delegates have other uses, the discussion here focuses on the event handling functionality of delegates.

Delegates are the basis for Events.A delegate can be instantiated by associating it either with a named or anonymous method.

Let us see example on events and delegates
Code: CSharp
using System;

namespace MyCollections
{
    using System.Collections;

    // A delegate type for hooking up change notifications.
    public delegate void ChangedEventHandler(object sender, EventArgs e);

    // A class that works just like ArrayList, but sends event
    // notifications whenever the list changes.
    public class ListWithChangedEvent : ArrayList
    {

        // An event that clients can use to be notified whenever the
        // elements of the list change.
        public event ChangedEventHandler Changed;

        // Invoke the Changed event; called whenever list changes
        protected virtual void OnChanged(EventArgs e)
        {
            if (Changed != null)
                Changed(this, e);
        }


        // Override some of the methods that can change the list;
        // invoke event after each
        public override int Add(object value)
        {
            int i = base.Add(value);
            OnChanged(EventArgs.Empty);
            return i;
        }


        public override void Clear()
        {
            base.Clear();
            OnChanged(EventArgs.Empty);
        }


        public override object this[int index]
        {
            set
            {
                base[index] = value;
                OnChanged(EventArgs.Empty);
            }
        }
    }
}


namespace TestEvents
{
    using MyCollections;

    class EventListener
    {
        private ListWithChangedEvent List;

        public EventListener(ListWithChangedEvent list)
        {
            List = list;

            // Add "ListChanged" to the Changed event on "List".
            List.Changed += new ChangedEventHandler(ListChanged);
        }


        // This will be called whenever the list changes.
        private void ListChanged(object sender, EventArgs e)
        {
            Console.WriteLine("This is called when the event fires.");
        }

        public void Detach()
        {
            // Detach the event and delete the list
            List.Changed -= new ChangedEventHandler(ListChanged);
            List = null;
        }
    }

    class Test
    {

        // Test the ListWithChangedEvent class.
        public static void Main()
        {

            // Create a new list.
            ListWithChangedEvent list = new ListWithChangedEvent();

            // Create a class that listens to the list's change event.
            EventListener listener = new EventListener(list);

            // Add and remove items from the list.
            list.Add("item 1");
            list.Clear();
            listener.Detach();
        }
    }
}
Lets us see an example on Delegates.

For use with named methods, the delegate must be instantiated with a method that has an acceptable signature.
Code: CSharp
using System;
// Declare delegate -- defines required signature:

delegate void SampleDelegate(string message);

class MainClass
{
    // Regular method that matches signature:
    static void SampleDelegateMethod(string message)
    {
        Console.WriteLine(message);
    }

    static void Main()
    {
        // Instantiate delegate with named method:
        SampleDelegate d1 = SampleDelegateMethod;

        // Instantiate delegate with anonymous method:
        SampleDelegate d2 = delegate(string message)
        {
            Console.WriteLine(message);
        };
        // Invoke delegate d1: d1("Hello");
        // Invoke delegate d2: d2(" World");
    }

}

Comments

Popular posts from this blog

WPF Tutorials - Binding Validation Rules

Bindings are a major part of WPF, and a big part of what makes it quick to create user interfaces in. They can be a little wordy and hard to debug sometimes, but overall they are extremely useful. Hopefully, after today's tutorial, you will find them even more useful - because today we are going to talk about building validation rules right into your bindings. Yup, you heard right - bindings in WPF have built in support for validation, and a number of the common controls have built in ways for displaying validation errors. Today we are going to build a simple little WPF application that has a TextBox in which the user is supposed to enter an IP Address (a v4 address - I was lazy and didn't want to write a validator for ipv6 as well :P). Below you can see a screenshot of the the app in action: A valid IPv4 address An invalid IPv4 address So the first thing that we need to do to add validation to a binding is to create a validation ru...

WPF Tutorial - Command Bindings and Custom Commands

Well, today we are going to take a look at the other side of that - creating and using your own custom command and command bindings. First we will take a look at setting up our own bindings to existing commands, and then we will see how to create our own commands from scratch. So an important thing to know, in order for command binding to make sense, is that (like many things in WPF) commands bubble. So when a command is triggered, it bubbles up along the WPF element tree from its origin (the command target, which we talked about in the previous tutorial), looking for an element that recognizes and can handle the command. The way that you can set up an element to handle a command is by creating a command binding. This can be done in either XAML or the code behind code - and we are going to take a look at the XAML first. <Window x:Class = "CustomCommandTest.CommandWindow"     xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"     ...

WPF Tutorial - Using The Built-In Commands

One of the features that WPF has is actually a blast from the past - something that MFC used to have, but was never included in WinForms. This is the concept of Commands. Commands are somewhat like events in that they are based on actions in the user interface, a command can get triggered (just like an event). But unlike regular events like 'click', commands are built in a way that makes it very easy to expose the same functionality at multiple places in an interface, with very little code duplication. On of the very useful features of commands is the fact that you actually get an automatic form of two way communication between the interface elements and the command they are bound too. This is because a command is made up of two main elements - Execute and CanExecute . So unlike in the regular world of events, when an action becomes unavailable, you can just have the CanExecute part of the command return false - and everything hooked to that command becomes d...