mercredi 4 octobre 2017

Why is the ?: operator asking for an explicit cast? [duplicate]

This question already has an answer here:

I have this piece of code

        StateMachine.State = string.IsNullOrEmpty(MyString) ?
            (IState) StateMachine.StateA : StateMachine.StateB;

I can also write it as

        if (string.IsNullOrEmpty(MyString))
            StateMachine.State = StateMachine.StateA;
        else
            StateMachine.State = StateMachine.StateB;

State is of type IState and StateA and StateB both implement IState.

In the first snippet the compiler demands an explicit cast, while in the second it is not needed. Why is it needed in the first example?

Aucun commentaire:

Enregistrer un commentaire