User defined collection with events : Collection Event « Data Structure « C# / CSharp Tutorial

Home
C# / CSharp Tutorial
1.Language Basics
2.Data Type
3.Operator
4.Statement
5.String
6.struct
7.Class
8.Operator Overload
9.delegate
10.Attribute
11.Data Structure
12.Assembly
13.Date Time
14.Development
15.File Directory Stream
16.Preprocessing Directives
17.Regular Expression
18.Generic
19.Reflection
20.Thread
21.I18N Internationalization
22.LINQ
23.GUI Windows Forms
24.Windows Presentation Foundation
25.Windows Communication Foundation
26.Workflow
27.2D
28.Design Patterns
29.Windows
30.XML
31.XML LINQ
32.ADO.Net
33.Network
34.Directory Services
35.Security
36.unsafe
C# / C Sharp
C# / C Sharp by API
C# / CSharp Open Source
C# / CSharp Tutorial » Data Structure » Collection Event 
11.46.1.User defined collection with events
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;

public class NotificationList<T> : Collection<T>{
    public event EventHandler<ItemInsertedArgs<T>> ItemAdded;

    protected override void InsertItem(int index, T item){
        EventHandler<ItemInsertedArgs<T>> handler = ItemAdded;
        if (handler != null){
            handler(this, new ItemInsertedArgs<T>(index, item));
        }
        base.InsertItem(index, item);
    }
}

public class ItemInsertedArgs<T> : EventArgs{
    public int Index;
    public T Item;

    public ItemInsertedArgs(int index, T item)
    {
        this.Index = index;
        this.Item = item;
    }
}

public class MainClass
{
    public static void Main()
    {

        NotificationList<int> list = new NotificationList<int>();

        list.ItemAdded += delegate(object o, ItemInsertedArgs<int> args) {
            Console.WriteLine("A new item was added to the list: {0} at index {1}",args.Item, args.Index);
        };

        for (int i = 0; i < 10; i++)
        {
            list.Add(i);
        }

    }
}
A new item was added to the list: 0 at index 0
A new item was added to the list: 1 at index 1
A new item was added to the list: 2 at index 2
A new item was added to the list: 3 at index 3
A new item was added to the list: 4 at index 4
A new item was added to the list: 5 at index 5
A new item was added to the list: 6 at index 6
A new item was added to the list: 7 at index 7
A new item was added to the list: 8 at index 8
A new item was added to the list: 9 at index 9
11.46.Collection Event
11.46.1.User defined collection with events
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.