Shallow copying a list with downcasting
Question
I have the class herichary as follows
CEntity---->CNode--->CElement
I have a
class Nodes : List<Cnode>
and
Class Elements : List<Element>
Node class contain common item common across different project Element class has item specific to a project.
I have to shallow copy the element list into the node list (basically down casting the elements to nodes)
Solution
Supposing you are using .net 3.0 or greater, the following code creates a NEW list with the SAME elements downcasted to CNodes:
List<CNode> shallowCopyNodesList = elements.Cast<CNode>().ToList();
Then (if not already present) you should create a constructor taking a List<CNode>
in Nodes class and do:
var shallowCopyNodes = new Nodes(shallowCopyNodesList);
OTHER TIPS
You could just do this:
List<CNode> nodes = new List<CNode>();
foreach (CElement element in elements) {
nodes.Add(element);
}
Where elements is a List.
You don't need to worry about casting back to CNode, because CElement inherits from that. The important thing to note is that the elements in the nodes list (in the example above), are in fact instances of CElement. If you wanted CNode you'd probably have to create a new instance of CNode using a copy constructor:
public CNode(CNode instance)
{
this.Property = instance.Property;
}
And add a new instance of CNode:
nodes.Add(new CNode(element));
You can use the Cast operator in LINQ.
var nodelist = elementList.Cast<CNode>()
.ToList();
What I have done is
nodes.addrange(ElementList.ConvertAll(new Converter<Elements, CNode>(ConvertElementsToNode))));
and
public static CNode ConvertElementsToNode(Element ele)
{
return ((CNode) ele);
} // ConvertElementsToNode
but will there be any performance/ memory issue in this approach.