menu

Sunday, September 11, 2016

Custom List with OnAdd Event

using System;
using System.Collections.Generic;
namespace Event
{
    class Program
    {
        static void Main(string[] args)
        {
            CustomList<int> list = new CustomList<int>();
            list.OnAdd += new EventHandler<CustomEventArgs<int>>(OnListAdd);
            list.Add(1);
        }
        static void OnListAdd(object sender, CustomEventArgs<int> e)
        {
            Console.WriteLine("Item: {0} added...", e.Item);
        }
    }
    class CustomList<T> : List<T>
    {
        public event EventHandler<CustomEventArgs<T>> OnAdd;
        public void Add(T item)
        {
            if (null != OnAdd)
            {
                CustomEventArgs<T> args = new CustomEventArgs<T>() { Item = item };
                OnAdd(this, args);
            }
            base.Add(item);
        }
    }
    class CustomEventArgs<T> : EventArgs
    {
        public T Item { get; set; }
    }

}

No comments:

Post a Comment