Search Unity

Having a covariance problem with a generic interface

Discussion in 'Scripting' started by diesoftgames, Oct 11, 2019.

  1. diesoftgames

    diesoftgames

    Joined:
    Nov 27, 2018
    Posts:
    122
    Here is my inheritance that I'm dealing with:

    Code (CSharp):
    1. interface IInputable<T> {}
    2. interface IOutputable<U> {}
    3. interface IStepIO<T, U> : IInputable<T>, IOutputable<U> {}
    4. class Step<T, U> : IStepIO<T, U> {}
    5. class Sequence<T, U> : Step<T, U> {}
    6. class RuleSequence: Sequence<Graph, Graph> {}
    If I create a new RuleSequence, I'm expecting to be able to pass it back in a method that returns IStepIO<Graph, Graph>, but I get a compiler warning that I cannot implicitly do that conversion. Something about my understanding of this situation is off because I was thinking that should work and I can't wrap my head around why it doesn't. Please note that I can't make the generic types co or contra variant because I have a getter setter in both IInputable and IOutputable which uses the generic type. If someone can explain this to me like I'm 5, it would be very much appreciated. Thank you!
     
  2. kru

    kru

    Joined:
    Jan 19, 2013
    Posts:
    452
    T and U are completely separate types all throughout the interface heirarchy.

    Understand that the compiler works with generic types and doesn't necessarily understand that your one concrete definition happens to be the same type. It sees two different types, and reports that it doesn't know how to generically convert between them, even though you happen to be creating a class where those are the same.

    Consider
    Code (csharp):
    1. class HowToConvertThis: Sequence<string, Vector3> { ... }
     
  3. diesoftgames

    diesoftgames

    Joined:
    Nov 27, 2018
    Posts:
    122
    EDIT: I'm a dummy, I solved this. I thought I was using the same Graph type in the function signature and the interface specification, but there were different types, hence the compiler rightfully saying it couldn't convert between the types. >___<
     
    Last edited: Oct 11, 2019