I have a generic class Zone<T> where T: Media.Medium
. In this class I have a method public void AddNode(Node node)
in which I have a statement node.ParentZone = this
which raises this compiler error:
Cannot implicitly convert type 'Zone< T >' to 'Zone< Media.Medium >'
But I can't understand why as public abstract class Node
has public Zone<Media.Medium> ParentZone
field and class Zone<T> where T: Media.Medium
is constrained by where T: Media.Medium
, so T is a Media.Medium
under every circumstance.
Here is the isolated code: (Full of Zone<T>
and a relevant part of Node
)
public class Zone<T> where T: Media.Medium
{
public readonly Type MediaType = typeof(T);
public readonly Guid ID = new Guid();
private readonly List<Node> _nodes = new List<Node>();
public void AddNode(Node node)
{
foreach (var port in node.GetPorts())
{
port.Medium = Activator.CreateInstance<T>();
}
// Compile error in the line below
node.ParentZone = this;
// Cannot implicitly convert type 'Zone< T >' to 'Zone< Media.Medium >'
_nodes.Add(node);
}
public List<Node> GetNodes() => new List<Node>(_nodes);
public void RemoveNode(Node node) => _nodes.Remove(node);
}
public abstract class Node
{
public Zone<Media.Medium> ParentZone;
...
}
UPDATE #1:
My goal by this code is this: I want to add Node
objects to Zone
objects, Zone
objects has a list of Node
objects. Whenever I add a Node
to a Zone
, I want to set that Zone
object as the parent of the Node
object.
I am open to any refactoring to achieve this goal. It shouldn't have to be in this way if there is a better one.