0

I have a few ObservableCollections with different object models, all inheriting from the same base model. For example:

class Food { }
class Pizza : Food { }
class Rice : Food { }
class Spaghetti : Food { }

and an ObservableCollection for each one:

ObservableCollection<Pizza> pizzaOC;
ObservableCollection<Rice> riceOC;
ObservableCollection<Spaghetti> spOC;

Then I have a method which has an ObservableCollection<Food> parameter, like so:

private bool CheckFood(ObservableCollection<Food> foodItems)
{
    // stuff here
}

The problem comes when I try to do the calls :

CheckFood(pizzaOC);
CheckFood(riceOC);
//...

Is there any way I can call a single method, but passing different types of ObservableCollections? And also, is there a way to find out in the method, which OC type has been passed?

dcastro
  • 66,540
  • 21
  • 145
  • 155
user3357962
  • 95
  • 3
  • 11

2 Answers2

2
private bool CheckFood<T>(ObservableCollection<T> foodItems) where T: Food
{
   ...
}

You can determine type of food passed to method with something like typeof(T) but it's better to move responsibility for logic to class itself

acrilige
  • 2,436
  • 20
  • 30
  • This is definitely the best way to do it. If you need to know the type of the object inside the method, then maybe it will be better to make this method virtual and override it with specific behaviour in classes which inherits from "FoodViewModel" You can check type of the Food object by: typeof(T) or by using "is" or "as" operators on collection or one of it's object. – Chris W. Mar 20 '14 at 09:33
  • Thanks this works, I'll accept it as soon as possible. A second question: is it also possible to find in the method which type is T? – user3357962 Mar 20 '14 at 09:33
1

If your method does not rely on the argument being explicitly ObservableCollection<T>, you could always code to the interface:

public bool CheckFood<TCollection, TItem>(TCollection collection)
    where TCollection : ICollection<TItem>, INotifyCollectionChanged
    where TItem : Food
{
    // something
}

This means if you want to use a custom "Observable Collection" you don't need to rely on it inheriting from ObservableCollection.

Additionally to find out what type has been passed through to the method you can call the following within the method:

var type = typeof(TItem);
Community
  • 1
  • 1
dav_i
  • 27,509
  • 17
  • 104
  • 136