Friedrich Ewald My Personal Website

Implementing events in List

If you want to subscribe for changes to a List<T> in C# it is very easy. All you need to do, is subclass List<T> and implement your own event handler. This could be done as following:

using System;
using System.Collections.Generic;

namespace FEwald
{
    public class MyList<T> : List<T>
    {
        /// <summary>
        /// EventHandler which is called when items are added.
        /// </summary>
        public event EventHandler ItemAdded;

        /// <summary>
        /// EventHandler which is called when items are deleted.
        /// </summary>
        public event EventHandler ItemRemoved;

        /// <summary>
        /// Adds an item to the list.
        /// </summary>
        /// <param name="item"></param>
        public new void Add(T item)
        {
            if (ItemAdded != null)
            {
                ItemAdded(item, EventArgs.Empty);
            }
            base.Add(item);
            
        }

        /// <summary>
        /// Adds a range of items to the list.
        /// </summary>
        /// <param name="collection"></param>
        public new void AddRange(IEnumerable<T> collection)
        {
            foreach (var item in collection)
            {
                Add(item);
            }
        }
        
        /// <summary>
        /// Removes an item from the list.
        /// </summary>
        /// <param name="item"></param>
        public new void Remove(T item)
        {
            if (ItemRemoved != null)
            {
                ItemRemoved(item, EventArgs.Empty);
            }
            base.Remove(item);
        }
    }
}


About the author

is an experienced Software Engineer with a Master's degree in Computer Science. He started this website in late 2015, mostly as a digital business card. He is interested in Go, Python, Ruby, SQL- and NoSQL-databases, machine learning and AI and is experienced in building scalable, distributed systems and micro-services at multiple larger and smaller companies.