Reputation: 47
I have a virtual method on a base class. Each time I override it, I want to return different object types. I know this is not possible, but what would be the best way to handle this situation?
Example of base method:
public virtual void clickContinue()
{
//click the continue button
}
And the method that overrides it:
public override myObject clickContinue()
{
//click then continue button
//return myObject
}
I need to do several similar overrides, all returning different objects. Again, I know this can't be done the way it's done above - I trying to figure out the best way to handle this situation.
Upvotes: 4
Views: 329
Reputation: 11607
I sense an abuse of the override mechanic. The idea behind it is that you do the same thing but with different parameters. The name of the method actually should tell you what it does. So how is it possible the the very same procedure returns void
(doesn't return anything) and on occasion returns something (non-void
)?
Are you sure you should not have two completely different methods? This would probably make the API clearer, too.
Otherwise, consider returning always object
, which happens to always be null
in case (instead) of the void
override.
Obviously, the generic way is better for type-safety. Returning object
means you abandon typing and take over casting manually.
Upvotes: 0
Reputation: 564413
I know this is not possible, but what would be the best way to handle this situation?
If you don't need a default implementation, you can potentially make the class generic, and return the generic type:
abstract class YourBase<T>
{
abstract T ClickContinue();
}
class YourOverride : YourBase<MyObject>
{
override MyObject ClickContinue()
{
//...
Upvotes: 7