Grit
Grit

Reputation: 31

C# generic cast conversion

I have a casting problem I am unable to solve :

in ClassA initialize function, I want to pass 'this' as parameter, but the compiler cannot cast from ClassA<T, U> to ClassA<ClassB<U>, U> knowing that they are the same (where T : ClassB<U>).

public class ClassA<T, U> : MonoBehaviour where T : ClassB<U>
{
    public void initialize()
    {
        T item =...
        item.Initialize(this); // Cannot implicitly convert from ClassA<T, U> to ClassA<ClassB<U>, U>.
    }
}

public class ClassB<T> : MonoBehaviour
{
    public virtual void Initialize(ClassA<ClassB<T>, T> mgr, T data)
    {
        ...
    }
}

Thanks.

Upvotes: 3

Views: 131

Answers (2)

Georg
Georg

Reputation: 5791

This does not work for classes. It only works if ClassB was an interface with an out type parameter as follows:

public interface IInterfaceB<out T>
{
   …
}

However, an out type parameter means that you can only use the type parameter T for return values in your IInterfaceB interface members, not for parameters.

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1064204

Consider: Elephant : Animal; this does not mean that List<Elephant> : List<Animal>, and you cannot cast a List<Elephant> to a List<Animal> for many reasons (including: that would let you Add(monkey) to the List<Elephant>, after casting to List<Animal>, because Monkey : Animal). It is exactly the same here, conceptually.

Upvotes: 10

Related Questions