When working with MVVM and Prism i find myself doing a lot of casting, as most parameters are interfaces
Ex
public void AddCrSubSystemsToPlant(IPlantItem plantItm, CRArticleItem crItm)
{
OSiteSubSystem itm = (OSiteSubSystem)crItm;
itm.PartData.Order = ((OSiteEquipment)plantItm).SubSystems.Count() + 1;
((OSiteEquipment)plantItm).SubSystems.Add(itm);
}
or
public void DeletePart(IPlantItem plantItem)
{
IEnumerable<IPlantItem> itmParent = GetParentPartByObjectId(_siteDocument, plantItem);
if (plantItem is OSiteEquipment)
((ObservableCollection<OSiteEquipment>)itmParent).Remove((OSiteEquipment)plantItem);
if (plantItem is OSiteSubSystem)
((ObservableCollection<OSiteSubSystem>)itmParent).Remove((OSiteSubSystem)plantItem);
if (plantItem is OSiteComponent)
((ObservableCollection<OSiteComponent>)itmParent).Remove((OSiteComponent)plantItem);
}
My question is , whats the cost involved. Are these operations costly memory or cpu wise, should they be avoided.
Any views?
I think the more important question is why are you doing so much casting?
In the first example:
Why is the first parameter type
IPlantItemif you keep casting it toOSiteEquipment? The same can be said about the second parameter.In the second example:
Why does GetParentPArtByObjectId return an
IEnumerable<IPlantItem>? If it were to return anICollection<IPlantItem>you wouldn’t have to cast toObservableCollection<T>.ObservableCollection<T>inherits fromCollection<T>which implements bothICollection<T>andICollection. You should be able to remove the item from the collection without even knowing its type.Now some advice.
Don’t cast the same object multiple times.
Don’t do this:
Do this instead
Use base types whenever possible. This will keep you from needing to cast so much. As previously stated, don’t cast to
ObserableCollection<T>to call a method onICollectionUse generics. If you need type specific logic, make an abstract base class(or just an interface if you don’t need any shared logic) with a generic parameter. Then make implementations of that class for each of the implementations of the interface. Methods can be generic, too. I can rewrite the second example as