Home
Manage Your Code
Snippet: Generic Collection with events (C#)
Title: Generic Collection with events Language: C#
Description: Collection<T> with events Views: 1802
Author: James Taylor Date Added: 2/15/2008
Copy Code  
1using System;
2using System.Collections;
3using System.Collections.Generic;
4using System.Collections.ObjectModel;
5using System.Text;
6
7public class NotificationList<T> : Collection<T>{
8    public event EventHandler<ItemInsertedArgs<T>> ItemAdded;
9
10    protected override void InsertItem(int index, T item){
11        EventHandler<ItemInsertedArgs<T>> handler = ItemAdded;
12        if (handler != null){
13            handler(this, new ItemInsertedArgs<T>(index, item));
14        }
15        base.InsertItem(index, item);
16    }
17}
18
19public class ItemInsertedArgs<T> : EventArgs{
20    public int Index;
21    public T Item;
22
23    public ItemInsertedArgs(int index, T item)
24    {
25        this.Index = index;
26        this.Item = item;
27    }
28}
29
30public class MainClass
31{
32    public static void Main()
33    {
34
35        NotificationList<int> list = new NotificationList<int>();
36
37        list.ItemAdded += delegate(object o, ItemInsertedArgs<int> args) {
38            Console.WriteLine("A new item was added to the list: {0} at index {1}",args.Item, args.Index);
39        };
40
41        for (int i = 0; i < 10; i++)
42        {
43            list.Add(i);
44        }
45
46    }
47}
Notes
http://www.java2s.com/Tutorial/CSharp/0220__Data-Structure/Userdefinedcollectionwithevents.htm