Hi,
I’ve got an interface IState which is used by several concrete classes, StateStop, StateForward and StateTurn etc.
In my while-loop I’ve got an if-sentence to compare if the currentstate and the new state is different or not.
I’m doing;
if (currentState != newState)
//Do stuff
But the if always triggers, even if the newState is the same as the old one. Then I remember something about ICompare, IComparable, IEquality etc. Which is the one I should implement so that the if-sentence works?
The line above calls AnalyzeSensors, and that returns a State object. This can for instance be a StateDriveForward, a StateTurn or a StateWaiting class.
If the new state is different than the previous one then I want to change into that new state.
One additional thing - the StateTurn class takes in a value to indicate how many degrees to turn the wheels. So the comparison must take this into consideration when comparing if the current StateTurn (with 30 degree turn) is different than the new StateTurn (with 45 degree turn).
@ Scalpel78 - Yes the problem is that you are returning a new instance for a state each time the state transition happens.
You do need a method to compare instances or implement IComparable. Or you can override Equality operator. You might need a base common class from which all state classes will derive in addition or instead of the common interface.
There are some other problems. The state management you have implemented gives unnecessary work to the garbage collector and fragmenting the memory. If you state changes happen often this might affect performance significantly.
If you want to keep classes for your states I would create a pool of the states instances and will reuse them, something like this:
IState[] states = { new StateTurn(),
new StateWaiting()
};
IState turnState = states[0];
(turnState as StateTurn).Angle = 45;
@ Scalpel78 - You can, but it is not very effective and not much simpler than just comparing two objects. You can compare using a.GetType() == b.GetType(). That would be true if objects are of the same type. And if the type is StateTurn then you can compare angles. Wrap it into a function it would be less than 10 lines of code.