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;
}
}
Container<T>is not variant. And in C# class can't be covariant - you'd need an interface to achieve what you need.