0

I have this class:

public class Itemcollection : Item
{
    public List<Item> Items{ get; set; }
}

And now I add the item(s) to a List

if (item is Itemcollection collection)
{
   list.AddRange(collection.items);
}
else
{
    list.Add(item);
}

Is there way to avoid the object check (if (item is Itemcollection collection)) and do this on a more generic way or somthing similar.

  • 4
    Sure: by not storing different things (single items and collections) into your list. In other words: by not inheriting `Item` in your `ItemColelction`. – MakePeaceGreatAgain Jun 24 '19 at 13:14
  • 1
    Are you sure you need the Itemcollection class? https://stackoverflow.com/questions/21692193/why-not-inherit-from-listt – Zohar Peled Jun 24 '19 at 13:17
  • _"Is there way to avoid the object check"_ - what's the problem with the current code? – SᴇM Jun 24 '19 at 13:19
  • @SᴇM this "if is .." can be avoided very easily here and that's exactly what op wants. – Joelius Jun 24 '19 at 13:20
  • @Joelius What OP wants and why is different things, is that giving him an error or unexpected results or something? – SᴇM Jun 24 '19 at 13:20
  • 5
    Why your `ItemCollection` class inherits from (a single) `Item`? That's confusing. It's like if an `University` inherits from a `Student`. – Tim Schmelter Jun 24 '19 at 13:21
  • @SᴇM I don't think this throws any errors it's just bad in general because the parameter would have to be of type object which usually seems to me like a design flaw. Or actually in this case it could be of type Item because of the weird inheritance scheme op has but still this pattern should usually be avoided. – Joelius Jun 24 '19 at 13:23
  • @TimSchmelter It's a recursive structure in which each item can contain more collections. It's used for modeling tree structures. – Servy Jun 24 '19 at 15:21
  • If you insist on this structure, you could add a virtual add(IList) method to item and override in itemcollection – the.Doc Jun 24 '19 at 20:01

2 Answers2

0

Well it depends what type is object item, but I think you can not do it without type check. You can wrap your code in a method and do that check there. Another option is method overloading.

Voyne
  • 1
  • 2
0

Rather than having certain items that have an Items collection, and some that don't, ensure that all of your items have a collection of items in them. Then simply have that collection contain a single item if the object logically represents a single value rather than a collection of values. That way in your code here (and elsewhere) where you process an item you can process all of the items, and if "all of the items" ends up being one item, so be it.

Servy
  • 202,030
  • 26
  • 332
  • 449