I am developing a generic class and related generic methods. I believe the problem I am about to describe has to do with Covariance, but I can't figure out what the compiler wants me to do.
Edit: adding code which shows how I populate the dict
There is abstract base class NetworkNode. Concrete class PowerNetworkNode inherits from it. Now I have a function which will not compile. What changes should I make to get this to compile and have the desired functionality?
In abc NetworkNode, we have
public abstract IDictionary<uint, NetworkNode>
hydrateNodes<NetworkNode>(string nodesTableName);
In the concrete class, PowerNetworkNode, this is overridden by
public override IDictionary<uint, NetworkNode>
hydrateNodes<NetworkNode>(string nodesTableName)
{
IDictionary<uint, PowerNetworkNode> returnDict =
new Dictionary<uint, PowerNetworkNode>();
// code elided
returnDict[Convert.ToUInt32(oid)] =
new PowerNetworkNode(oid, minPow, maxPow, edges, fuelType, ngID);
// NetworkNode doesn't have all the fields that PowerNetworkNode has.
return returnDict;
}
The compiler error message is:
Error CS0266 Cannot implicitly convert type
'System.Collections.Generic.IDictionary<uint,
CImodeller.Model.NetworkElements.PowerNetworkNode>' to
'System.Collections.Generic.IDictionary<uint, NetworkNode>'.
An explicit conversion exists (are you missing a cast?)
When I change the code to this:
public override IDictionary<uint, NetworkNode>
hydrateNodes<NetworkNode>(string nodesTableName)
{
IDictionary<uint, NetworkNode> returnDict =
new Dictionary<uint, PowerNetworkNode>();
// code elided
return returnDict;
}
in which the line with "new Dictionary" now creates one with NetworkNode and not PowerNetworkNode, the compiler states
Error CS0266 Cannot implicitly convert type
'System.Collections.Generic.Dictionary<uint,
CImodeller.Model.NetworkElements.PowerNetworkNode>' to
'System.Collections.Generic.IDictionary<uint, NetworkNode>'.
An explicit conversion exists (are you missing a cast?)
I understand what this means, but I don't know what I should change to get it to work.