Zeke Sanders
Zeke Sanders

Reputation: 13

Operator cannot be applied to operands of generic type

Im writing a hierarchal state machine in C# and im using a generic type S in which will be fed an enum with different states for the different state machines. I get the following error. Check the comment in the code.

public interface IStateMachine
{
    public void fireTrigger(GameWideTrigger trigger);
}

public class StateTransition<T, S>
{
    public S StartState { get; private set; }
    public T Trigger { get; private set; }
    public S EndState { get; private set; }
}

public class StateMachine<S> : IStateMachine
{
    private List<StateTransition<GameWideTrigger, S>> transitions;

    public void fireTrigger(GameWideTrigger trigger)
    {
        foreach (StateTransition<GameWideTrigger, S> transition in transitions)
        {
            if (transition.StartState == CurrentState)  // CS 0019 Operator 'operator' cannot be applied to operands of type 'S' and 'S'
        }
    }
}

Upvotes: 0

Views: 663

Answers (1)

Zeke Sanders
Zeke Sanders

Reputation: 13

Thank you canton7 for the correct answer:

== can mean a couple of different things (reference equality, a user-provided operator) and the compiler needs to figure out at compile-time which of those it is. It can't do that if it doesn't know anything about the type: S might be a value type with no == operator, and then what should happen? If you constrain S to be a reference type (where S : class) then the == will be allowed, as a reference comparison. Alternatively you can do EqualityComparer<T>.Default.Equals(x, y), which will call the type's Equals implementation

Upvotes: 1

Related Questions