2

I need a list of applicable view models and am debating whether to try to make a composite collection or to create a shared interface that they inherit from. Is one method preferred?

I assume that composite collection maintains an index of the items that is independent of the underlying collections so that it is possible to have Composite Collection item # 0 (item type A) 1 (item type B) 2 (item type A) 3 (item type A), and maintain the ordering in the list.

Are there any major differences between the two methods?

I thought I would explain in a bit more detail what I typically do. Typically I need a list of selectedItems and I could just have create an ObservableCollection of type Object and then have the treeview apply different datatemplates based on the data type. However, I thought it was better to have some type safety and know that not just any object is being thrown in the collection, so I implement an interface instead. However, at times I feel ridiculous because there are not enough shared properties between the objects implementing the interface, so I feel ridiculous trying to make a shared interface.

It's possible that implementing a composite collection with separate lists of each of the possible types would make more sense.

James Joshua Street
  • 3,259
  • 10
  • 42
  • 80

1 Answers1

2

According to msdn (on CompositeCollection):

Enables multiple collections and items to be displayed as a single list.

Unless this is what you need (which I don't think it is), you should go for ObservableCollection<T>. Since it is generic, it saves you from unnecessary, error-prone castings. Removing the need to cast its elements also leads to a performance improvement when used with value types (i.e., no boxing/unboxing).

Also, it is hard to tell whether making all your view models implement a shared interface is a good option, without knowing more about the view models. Ask yourself: does that make sense? Is there truly a relationship between them? Will clients of the collection be able to treat instances of that interface equally, regardless of their real type?

dcastro
  • 66,540
  • 21
  • 145
  • 155