I have an abstract base class P. I have two classes that inherit P called I and O.
I have a Get() method in my repository that returns P. This method always returns an instance of either I or O depending on a value.
public P Get(string pci)
{
var a = GetAByPCI(string pci);
if(a == 1)
return new I();
else if(a == 2)
return new O();
else
// throw exception here.
}
When I call this method from another location I need to check and cast the type.
P p = PRepository.Get("200");
if(p is I)
I i = (I)p;
I’d like to avoid having to check and downcast every time p above is used. I feel as though I’m doing some fundamentally wrong here, but am not certain.
Update:
The derived types I & O have additional properties that need to be used but only pertain to that specific type. P has many abstract properties that are implemented in inheriting types. Downcasting is the only way I can get to the concrete types as needed?
Maybe the logic is entirely wrong.
The whole point of having a base class is to avoid having to deal with the subclass itself. Just add an abstract method to the base class and have it implemented in the sub-classes. This way, the calling code will simply call the method without having to do any casts. This is basic polymorphism.