With this generics code why am I getting “Argument 1: cannot convert from 'ToplogyLibrary.RelationshipBase<TNode>' to 'TRelationship'”
-
26-09-2019 - |
Question
Any see why I'm getting a "Argument 1: cannot convert from 'ToplogyLibrary.RelationshipBase' to 'TRelationship'" in the code below, in CreateRelationship() ?
public class TopologyBase<TKey, TNode, TRelationship>
where TNode : NodeBase<TKey>, new()
where TRelationship : RelationshipBase<TKey>, new()
{
// Properties
public Dictionary<TKey, TNode> Nodes { get; private set; }
public List<TRelationship> Relationships { get; private set; }
// Constructors
protected TopologyBase()
{
Nodes = new Dictionary<TKey, TNode>();
Relationships = new List<TRelationship>();
}
// Methods
public TNode CreateNode(TKey key)
{
var node = new TNode {Key = key};
Nodes.Add(node.Key, node);
return node;
}
public void CreateRelationship(TNode parent, TNode child)
{
// Validation
if (!Nodes.ContainsKey(parent.Key) || !Nodes.ContainsKey(child.Key))
{
throw new ApplicationException("Can not create relationship as either parent or child was not in the graph: Parent:" + parent.Key + ", Child:" + child.Key);
}
// Add Relationship
var r = new RelationshipBase<TNode>();
r.Parent = parent;
r.Child = child;
Relationships.Add(r); // *** HERE *** "Argument 1: cannot convert from 'ToplogyLibrary.RelationshipBase<TNode>' to 'TRelationship'"
}
}
public class RelationshipBase<TNode>
{
public TNode Parent { get; set; }
public TNode Child { get; set; }
}
public class NodeBase<T>
{
public T Key { get; set; }
public NodeBase()
{
}
public NodeBase(T key)
{
Key = key;
}
}
Solution
With these line:
where TRelationship : RelationshipBase<TNode>, new()
You're not saying that TRelationship = RelationshipBase but TRelationship inherits from a RelationshipBase.
But you can't implicity convert a base class to its descendant.
So, you really need this:
List<TRelationship>
or
List<RelationshipBase<TNode>>
this is enough for you ?
Or maybe looking your code: why don't you change this line:
var r = new RelationshipBase<TNode>();
with:
var r = new TRelationship();
??
EDIT: as AakashM said I've supposed you meant TNode and not TKey
OTHER TIPS
Your constraint for TRelationship
says RelationshipBase<TKey>
. Did you perhaps mean it to say RelationshipBase<TNode>
?
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow