Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I detect adds to a generic list in C# 4.0?

I have a subclass of List<Location> called LocationList. This is a convenient way for us to add other properties (like IsExpanded and such that we can use in the UI. Good enough. But now, we want each location to be aware of its parent. As such, we need to be notified when something is added to LocationList, but you can't override Add and Remove. While we can use ObservableCollection, that's more of a View/ViewModel construct. This is pure model data.

Sure we could manually set the parent when adding it to the collection, but I hate non-automated logic like that as there's nothing to enforce its set correctly. Letting the collection (well, List) automatically say 'Hey... you're being added, so I'll set your parent to the class that owns me." is what I'm after.

My thought is to instead of subclass List<Location> to instead just create a straight class that uses a List<Location> internally, and then I can simply expose my own Add/Remove methods and handle the adjustments to 'Parent' in there. However, doing so breaks being able to enumerate over the internal collection since it's inside.

That said, is there any way to either listen to changes to List<Location>, or at least delegate its IEnumerable interface from the wrapped object to its wrapper?

like image 426
Mark A. Donohoe Avatar asked Jul 07 '11 04:07

Mark A. Donohoe


People also ask

How to check if an item exists in a list in c#?

List<T>. Contains(T) Method is used to check whether an element is in the List<T> or not.

How to check if a list contains a string c#?

if (myList. Contains(myString)) string element = myList. ElementAt(myList. IndexOf(myString));

Is generic list C#?

C# List (List<T>) In c#, List is a generic type of collection, so it will allow storing only strongly typed objects, i.e., elements of the same data type. The size of the list will vary dynamically based on our application requirements, like adding or removing elements from the list.


1 Answers

Change your LocationList to inherit from Collection<Location> instead. I don't know why List<T> isn't sealed, but it's not extendable.

Source: Framework Design Guidelines, Second Edition, Page 251:

List<T> is optimized for performance and power at the cost of cleanness of the APIs and flexibility.

like image 79
Michael Stum Avatar answered Sep 20 '22 18:09

Michael Stum