Results 1 to 3 of 3

Thread: [RESOLVED] Raise event when items added to list

Threaded View

  1. #1

    Thread Starter
    Hyperactive Member BramVandenbon's Avatar
    Join Date
    Jan 2002
    Location
    Belgium
    Posts
    502

    Resolved [RESOLVED] Raise event when items added to list

    Hi,

    Here I am with another problem that has been annoying me for a long long time. Usually I fix it in a creative way, but I would really like to find out if there is a default approach to this problem.

    Introduction:

    Let's say you have a class that looks like this:

    Code:
    public class Shop{
        private List<Product> lstAvailableProducts = new List<Products>();
    
        public List<Product> AvailableProducts{
            get { return lstAvailableProducts; }
        }
    }
    The available products list can not be replaced by another list (because there is no set-property), but products can be added to it and removed from it like this:
    Code:
    Shop s = new Shop();
    Product p = new Product();
    s.AvailableProducts.Add(p);
    Problem:
    Now let's say I want to implement the observer pattern or add an event like: AvailableProductsChanged

    I have come across this problem over and over again. It is always a bit annoying. Because the Shop does not know when products are added to it or Removed from it. Shop does not really have any control of what happens to the list.

    My usual solution:
    - I create an "ObservableList<T>"-class which has events of its own and extends the List<T> class. Next I implement the events in my "Shop"-class. However, extending a list feels wrong. And if it was the way to go, then it makes you wonder why the List doesn't have these events in the first place.

    OR

    - I create 2 new methods: AddProduct(), RemoveProduct() ... however this brings up new problems like: Should I remove the get-property, to avoid that users add Products directly in the list? and How can I loop through the list if it is private?

    OR

    - I could make the Shop derive from a List<T> directly. But that is really a terrible solution. It would be impossible to add other lists (such as: List<Cars> CarsOnTheParking, List<Machines> ITInfrastructure) to the Shop.

    Your usual solution:

    Does this problem also occure somewhere in the .NET framework itself, and how did they solve it?
    What do you prefer?
    Or is there another (better) way?

    Thank you in advance once again
    Last edited by BramVandenbon; Nov 3rd, 2006 at 04:14 AM.
    ____________________________________________

    Please rate my messages. Thank you!
    ____________________________________________
    Bram Vandenbon
    http://www.bramvandenbon.com

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width