2

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.

Ilenca
  • 301
  • 2
  • 10
  • 2
    Why are you performing the cast at all, and not just declaring it as IQuestValidator c (or var)? – Metheny Apr 27 '19 at 17:17
  • @Metheny I want to cast it to generic IQuestValidator because I have an "injector" that based on a type it returns that generic class, like this refs = new Dictionary>(); and I need all Quest validator have a common interface – Ilenca Apr 27 '19 at 17:36
  • check this: https://stackoverflow.com/questions/12365993/c-sharp-casting-an-inherited-generic-interface and https://stackoverflow.com/questions/2033912/c-sharp-variance-problem-assigning-listderived-as-listbase and https://learn.microsoft.com/en-us/dotnet/standard/generics/covariance-and-contravariance#InterfaceCovariantTypeParameters – Greg Apr 27 '19 at 18:14
  • 1
    Possible duplicate of [C# variance problem: Assigning List as List](https://stackoverflow.com/questions/2033912/c-sharp-variance-problem-assigning-listderived-as-listbase) – Greg Apr 27 '19 at 18:14
  • Thanks @Greg. I think my case is different from the questions that use List, but the first link is near of what I'm trying to do, but I use Quest as Class and in that example Quest would be an interface. I will try it and see if it works – Ilenca Apr 27 '19 at 19:14

1 Answers1

1

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.