• 0

[C#] Need to raise event on Add() method for List<T>


Question

I have a variable declared as List<Panel> and I need to raise an event every time I add a panel to the list and I need to do this in the same class has the variable is declared (just beucase I tried to subclass Collection<T> and overriding InsertItem(), but wasn't able to access variables/methods on the same class ehere the Collection<Panel> would be declared.

Can anyone help me out? How can I raise an event on the Add() method of List<T>?

8 answers to this question

Recommended Posts

  • 0

Because you can't override the Add() method of the Generic List<T> class, trying to add events to it will be useless. What you can do, is create a class which extends the System.Collections.CollectionBase class. The CollectionBase class providers an internal collection, to which you add your own Add(), Remove(), Insert() etc. methods to create a externally-strong collection. With the code below, I am defining my custom collection, with an event which can be fired when a string is added to the collection:

public class StringCollection : CollectionBase
	{
		public delegate void StringCollectionEventHandler(object sender, StringEventArgs e);
		public event StringCollectionEventHandler StringAdded;

		public int Add(string item)
		{
			int index = this.InnerList.Add(item);
			if (StringAdded != null)
			{
				StringAdded(this, new StringEventArgs(item));
			}
			return index;
		}
	}

	public class StringEventArgs {
		private string value = string.Empty;

		internal StringEventArgs(string value)
		{
			this.value = value;
		}

		public string Value { get { return value; } }
	}

I make sure I declare both the collection, and my event arguments that I want the event to carry. What happens here is that when the user attaches an event to my collection, my collection will fire that event, passing through the item that was added:

class Program
	{
		static void Main(string[] args)
		{
			StringCollection collection = new StringCollection();
			collection.StringAdded += new StringCollection.StringCollectionEventHandler(collection_StringAdded);
			collection.Add("This		collection.Add("Is		collection.Add("A		collection.Add("Test		collection.Add("String		Console.ReadKey();
		}

		static void collection_StringAdded(object sender, StringEventArgs e)
		{
			Console.WriteLine(string.Format("'{0}' was added to the collection", e.Value));
		}
	}

  • 0

While searching on how to override the Add() method of List<T>, I found someone suggestion overriding the InsertItem() method of Collection<T>. And it works as I wanted. The only problem I was having, was with delegates and events and how would I call them from a different class. But I managed to do it...

Thanks anyway for your help Antaris! :)

  • 0

I see you've already found a solution, but had you considered using ObservableCollection<T>?

It has a built in CollectionChanged event that might be useful for you. This appears to only exist in .NET 3.0, so if you are still only using 2.0, then it really won't help you. If your use of delegates is sufficient, then ignore this, but I thought it might come in handy.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • I happen to try it today not knowing about the update and was happily surprised; it is great.
    • Hello, Hardware Support Applications are a special kind of Microsoft Store app and have to go through additional checks and certifications because they can communicate directly with their driver, which means that a vulnerability in one of them could allow an attacker access to kernel space memory through the HSA ←→ device driver interface.  In other words, a BYOVD (bring your won vulnerable driver) attack, but with the HSA being used as an extra step. Remember, the Microsoft Store is strategic to Microsoft's long-term goals: they see it as the means to get the same 30% of every application sale that Apple and Google get through their stores, which is why it has been a fixture of Windows since Windows 8 was introduced in 2012 despite a low adoption rate.  Microsoft cannot afford to have anyone get an app through their store which causes a security issue for their end users.  Even if the app was written by and uploaded to the Microsoft Store by a partner, it is Microsoft's name on the store, and they are the ones that will have reputational/brand damage if they allow something malicious into their store. Regards, Aryeh Goretsky  
    • This is more from my childhood, when nickelodeon just launched and had to license shows to have something to air. Left a big an impact, but probably more emotion positive / childhood thing. Europe got the follow up season's decade's latter with the animation studio that did Air Bender but never licenses for the US. I miss the day's of longer intro's. Nier (PS3) Intro is epic, and was very unexpected.  PS1 Xengears was also epic and an amazing game.  
    • Sayan Sen, do you think one day an image of the Windows Vista desktop or the wallpaper could be used in the primary image of an article? (When I think of CDs and DVDs I think of that release of Windows and of earlier releases; it is the one that debuted IMAPI 2.0 and other features.)
    • Big fan of EAC Here's a good non-default naming scheme I found on the web (can't take credit) File Name Scheme - %albumartist%\%year% - %albumtitle%\%tracknr2% %title% Various Artists Naming Scheme - Various Artists\%year% - %albumtitle%\%tracknr2% %title% Also, I need test but there is a new flac.exe binary & dll you can drop in the folder to upgrade flac support. I did this pre EAC 1.8. EAC 1.8 did upgrade it to 1.4.3. Flac 1.5.0 came out this year. https://ftp.osuosl.org/pub/xiph/releases/flac/ I don't know how much of a difference / impact will make.
  • Recent Achievements

    • Week One Done
      Ricky Chan earned a badge
      Week One Done
    • Week One Done
      maimutza earned a badge
      Week One Done
    • Week One Done
      abortretryfail earned a badge
      Week One Done
    • First Post
      Mr bot earned a badge
      First Post
    • First Post
      Bkl211 earned a badge
      First Post
  • Popular Contributors

    1. 1
      +primortal
      484
    2. 2
      +FloatingFatMan
      263
    3. 3
      snowy owl
      240
    4. 4
      ATLien_0
      227
    5. 5
      Edouard
      188
  • Tell a friend

    Love Neowin? Tell a friend!