• 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

    • iPadOS 26 is now official with improved windowing, menu bar, 'Liquid Glass' redesign, more by Taras Buria As expected, today, at WWDC 2025, Apple announced iOS 26 and other operating systems that now carry the 26 version number (for simplicity). iPadOS is also part of the big redesign, and it is now official with the new Liquid Glass design, improved window controls, a Mac-like menu bar, file management enhancements, and more. In addition to the general Liquid Glass redesign, which is now present across all of Apple's operating systems, iPadOS 26 received several iPad-exclusive upgrades. It now has a reworked windowing system that helps you organize and switch between apps. You can finally place and resize apps exactly how you want. Plus, iPadOS now has familiar window controls: three buttons for closing, minimizing, and resizing your app. Straight from macOS. Apps can now remember their previous size and position, and Expose can show you all open windows. Finally, iPadOS now has a menu bar, which is another thing that comes from macOS. It gives access to common actions, commands, and features. Developers can customize the menu bar in their apps and specify what features are available there. Apple is also upgrading the Files app with a reworked List view, which now shows more details about your files and the ability to expand or collapse folders. Plus, you can customize folders with colors and emojis, pin folders to the dock, and set default apps for file types. When working with long-running processes, background tasks show up as live activities, so that you can track Final Cut exports or the Files app moving stuff around. Other changes in iPadOS 26 include improved audio controls and the ability to select audio input source and record audio with voice isolation. The Journal app is now available on the iPad, Notes received markdown support, and Calculator now supports 3D graphing capabilities. You can learn more about iPadOS 26 in the official announcement post here.
    • That same Brave that tried to insert their own ads instead of blocked ones?
    • lol more spy centers - great work tiny hat gov. The surveillance state is licking it's chops so Palantir can know your every thought and move. 1984 is already here folks. Maybe start fighting it instead of contributing to it? Here is a good start - stop putting your entire life on a computer. Walk outside and see real life.
    • How long until Microsoft, Google, and others go (back) to this design trend?
  • Recent Achievements

    • Rookie
      CHUNWEI went up a rank
      Rookie
    • Enthusiast
      the420kid went up a rank
      Enthusiast
    • Conversation Starter
      NeoToad777 earned a badge
      Conversation Starter
    • Week One Done
      VicByrd earned a badge
      Week One Done
    • Reacting Well
      NeoToad777 earned a badge
      Reacting Well
  • Popular Contributors

    1. 1
      +primortal
      476
    2. 2
      +FloatingFatMan
      279
    3. 3
      ATLien_0
      255
    4. 4
      Edouard
      204
    5. 5
      snowy owl
      200
  • Tell a friend

    Love Neowin? Tell a friend!