Lets say I have a high level interface IRobot
public interface IRobot
{
Boolean DoAction(object action);
}
And two classes that implement this interface
public class WalkingRobot : IRobot
{
public enum WalkAction { SLOW, FAST };
public new Boolean DoAction(object inAction)
{
WalkAction action = (WalkAction)inAction;
// Does the action based on argument
return true;
}
}
public class TalkingRobot : IRobot
{
public enum TalkAction { ENGLISH, GERMAN };
public new Boolean DoAction(object inAction)
{
TalkAction action = (TalkAction)inAction;
// Does the action based on argument
return true;
}
}
If I then have a List<IRobot>
that contain an instance of both of these classes
WalkingRobot walker = new WalkingRobot();
TalkingRobot talker = new TalkingRobot();
List<IRobot> robots = new List<>();
robots.Add(walker);
robots.Add(talker);
Will I be able to iterate over the List<>
and compare each IRobot
with my instances I have created?
WalkAction wAction = WalkAction.FAST;
TalkAction tAction = TalkAction.ENGLISH;
foreach(IRobot robot in robots)
{
if(robot == walker)
robot.DoAction((object)wAction);
if(robot == talker)
robot.DoAction((object)tAction);
}
Unless there's an ==
overload that you haven't shown, you're just comparing whether two references are equal - that's fine. You don't even need to cast wAction
and tAction
to object
, as you can just use the implicit conversion:
foreach(IRobot robot in robots)
{
if (robot == walker)
{
robot.DoAction(wAction);
}
else if (robot == talker)
{
robot.DoAction(tAction);
}
}
That will work, but overall this isn't great object-oriented design by a long way. You're not the robots in the same way, and each robot has to cast their action to the right type.
If this is just meant to be a question about comparing objects with ==
, that's fine - but I would steer away from the rest of the code in terms of a design.
See more on this question at Stackoverflow