Ilenca
Ilenca

Reputation: 301

Error casting class to its interface with generic type (when also casting generic type to its base)

Hello I have the next problem casting classes. I have a Quest class that others inherit

public class Quest{}

public class QuestChild: Quest{}

I use a generic validator that expects to receive some type of Quest

public interface IQuestValidator<in T> where T:Quest
{
    bool IsCompleted(T quest);

    bool IsFailed(T quest);
}

public class QuestValidator<T>: IQuestValidator<T> where T: Quest
{    
    public bool IsCompleted(T quest)
    {
        return false;
    }

    public bool IsFailed(T quest)
    {
        return true;
    }
}

When I create the validator for each derived class of Quest, I want to cast it to its Base clase like this:

    IQuestValidator<Quest> c = (IQuestValidator<Quest>)new QuestValidator<QuestChild>();

But when I execute this line, it returns the error "InvalidCastException". Why this happens or how could I solve this to cast correctly?

Note: It seems similar to this question C# variance problem: Assigning List<Derived> as List<Base>, but since I'm not using IEnumerable I can't do the same.

Upvotes: 2

Views: 63

Answers (1)

user11238604
user11238604

Reputation:

The corresponding class is invariant, so there's no way the cast would be possible! Try rethinking your design to remove the demand for the desired cast.

Upvotes: 1

Related Questions