I have a few Abstract classes that have the core functionality of some UserControls in my project. I also have two separate implementations both deriving from the Abstract classes; lets call them AbstractImpl1 and AbstractImpl2. In addition, I have Collections of the Abstract UserControls that I iterate through in several places.
The issue I’m having is InvalidCastExceptions – I need to iterate through the implementations rather than the abstact UserControls to get to certain properties (visual). Is there a clean way of dealing with this other than doing a try/catch?
Example:
In my project I have Abstract classes: AbsUserControl
Then I have two separate implementations of them: AbstractImpl1 and AbstractImpl2
In my main form I have ObservableCollection<AbsUserControl> absControlCollection and then iterating through items I do foreach(AbstractImpl1 userControl in absControlCollection) to be able to access the visual aspects. The issue is that ObservableCollection<AbsUserControl> absControlCollection could either be comprised of AbstractImpl1 or AbstractImpl2 objects.
Is there a clean way of dealing with this? Right now, every place I iterate through the objects in absControlCollection I surround it with a try/catch block, trying to iterate through AbstractImpl1 objects then catching an InvalidCastException and proceeding with iterating through AbstractImpl2 objects.
Let me know if any more information is needed. Thanks!
An alternative to
OfType; casting without exceptions: