I have a list like this:
List list = new List
How to handle adding new position to this list?
When
You could inherit from List and add your own handler, something like
using System;
using System.Collections.Generic;
namespace test
{
class Program
{
class MyList : List
{
public event EventHandler OnAdd;
public new void Add(T item) // "new" to avoid compiler-warnings, because we're hiding a method from base-class
{
if (null != OnAdd)
{
OnAdd(this, null);
}
base.Add(item);
}
}
static void Main(string[] args)
{
MyList l = new MyList();
l.OnAdd += new EventHandler(l_OnAdd);
l.Add(1);
}
static void l_OnAdd(object sender, EventArgs e)
{
Console.WriteLine("Element added...");
}
}
}
Be aware that you have to re-implement all methods which add objects to your list. AddRange() will not fire this event, in this implementation.
We did not overload the method. We hid the original one. If you Add() an object while this class is boxed in List, the event will not be fired!
MyList l = new MyList();
l.OnAdd += new EventHandler(l_OnAdd);
l.Add(1); // Will work
List baseList = l;
baseList.Add(2); // Will NOT work!!!