Search code examples
c#genericsdowncast

Shallow copying a list with downcasting


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);