Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# generic cast conversion

Tags:

c#

casting

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.

like image 619
Grit Avatar asked Feb 23 '26 19:02

Grit


1 Answers

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.

like image 61
Marc Gravell Avatar answered Feb 26 '26 08:02

Marc Gravell