Type typeThing = gumballMachine.GetState().GetType();
if (typeThing == typeof(NoQuarterState)) { ... }
IState state;
public IState GetState() {
return state;
}
public class NoQuarterState : IState { ... }
I’m using a gumballMachine app from Ch10 of Head First Design Patterns. full code here This works.
Problem: typeThing above smells! Is there a better way?
You could use the
isoperator:This of course would result in
truefor all types that inherit fromNoQuarterStateas well though. Based on your example this shouldn’t be a problem.The question is why do you have to distinguish by type in the first place? Usually that’s a sign that a better design is in order, i.e. maybe the the strategy pattern or another use of polymorphism could help.