0

I am building a StateMachine. For my States I use an interface:

public interface IState
{
    void Enter();
    void Execute();
    void Exit();
}

I always have a IState currentState active, I would like to check which type of State it is. Lets say I have WalkingState and RunningState, I would like to check which one is currently Active.

I tried something like:

public bool IsCurrentState<T>()
{
    return (Type)currentState == typeof(T);
}

But It does not allow me to cast currentState to a Type, and nothing else I've tried has worker either.

Majs
  • 607
  • 2
  • 7
  • 20

3 Answers3

3

This will work:

currentState.GetType() == typeof(T)

Edit:

As mentioned in Rajan Prasad's answer, you can use is. is and GetType() == typeof(T) behave differently. Primarily:

  • If A : B, instanceOfA is instanceOfB is true while instanceOfA.GetType() == typeof(B) is false.

If you have only 1 level of inheritance from IState (i.e only FirstLevelState : IState, no SecondLevelState : FirstLevelState) use is, it is more performant and has fewer edge cases. Otherwise, use GetType() == typeof(T).

This question details type checking method differences: Type Checking: typeof, GetType, or is?.

JeremyTCD
  • 695
  • 1
  • 6
  • 11
2

You should use something like this

public bool IsCurrentState<T>() {
    return currentState is T ;
}
Rajan Prasad
  • 1,582
  • 1
  • 16
  • 33
0

Also you can use Type.IsAssignableFrom (). He requires two instaces of System.Type, because you havent to have statically declared type. It differents on the other parts your code, but you should know about it.

kacperfaber
  • 84
  • 1
  • 8