Each item has an interface, IItem. As well as this, there is a interface known as IDrawableItem which inherits from Item.
The code below, is trying to draw a drawable item, but cannot as the collection this class stores accepts only IItem. You can add anything that inherits from IItem to this class, but using other methods can only be achieved by casting.
foreach (var item in Items) {
item.Draw(); // The casting would go here.
}
I know how to cast, as etc… but is this acceptable? Is it a best practice?
Just wondering if there are other ways to handle such scenarios.
Use
Enumerable.OfTypeto extract only those elements ofItemsthat implementIDrawableItem:To address the question that Nanook asked in the comments the above code will probably be translated into code equivalent to the following:
Of course, really there is an iterator behind the scenes that looks something like this:
So, what this shows is that we probably only iterate through
Itemsonce. Of course, there is no requirement thatOfTypeis implemented like the above but this is the sensible thing to do.