0

So I generalized my code to the below example and I get the following compile error. My question is 'Why is assigning the reference back to 'container' not allowed?'. My assumption was that by restricting the type T to inherit from Element that 'this' should be easy to cast to Container<Element>. The point of this code is to keep a reference to the container in each element object in the case that the object (which gets passed around a lot) needs to have a reference to where it is contained.

Compilation error (line 16, col 23): Cannot implicitly convert type 'Container<T>' to 'Container<Element>'

If I add a type cast to the line containing 'this' I get the below instead.

Compilation error (line 16, col 23): Cannot convert type 'Container<T>' to 'Container<Element>'

using System;

public class Element
{
    public int datum;
    public Container<Element> container;
}

public class Container<T> where T : Element {

    T[] data;

    public Container() {
        data = new T[1];
        data[0].datum = 4;
        data[0].container = this;
    }

}
2
  • That's because Container<T> is not variant. And in C# class can't be covariant - you'd need an interface to achieve what you need. Commented Aug 27, 2016 at 4:53
  • Possible duplicate of Creating a generic array at runtime Commented Aug 27, 2016 at 4:56

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.