Search code examples
c#data-structurescastingtree

Cast/Convert tree structure to different type


If I have the class:

class NodeA
{
      public string Name{get;set;}
      public List<NodeA> Children {get;set;}
      // etc some other properties
}

and some other class:

class NodeB
{
      public string Name;
      public IEnumerable<NodeB> Children;
      // etc some other fields;
}

If I need to convert a NodeB object to of type NodeA what will be the best approach? Create a wrapper class? If I have to create a wrapper class how could I create it so that all the wpf controls will still be able to successfully bind to the properties?

  • Reason why I need to create such cast:

    There was an old algorithm that was used on a program that return the list of symbols (IMemorySymbol) in a compiled program. We have worked and created a new algorithm and the fields and properties are somewhat different (ISymbolElem). We need to perform a temporary cast in order to display the properties in the view of the wpf application.


Solution

  • A couple approaches...

    Copy Constructor

    have a NodeA and NodeB contain a constructor which takes the opposite:

    class NodeA 
    { 
        public string Name{get;set;} 
        public List<NodeA> Children {get;set;} 
    
        // COPY CTOR
        public NodeA(NodeB copy)
        {
            this.Name = copy.Name;
            this.Children = new List<NodeA>(copy.Children.Select(b => new NodeA(b));
            //copy other props
        }
    } 
    

    Explicit or Implicit Operator

    explicit you would cast like NodeA a = (NodeA)b;, while implicit you can skip the parens.

    public static explicit operator NodeA(NodeB b)
    {
        //if copy ctor is defined you can call one from the other, else
        NodeA a = new NodeA();
        a.Name = b.Name;
        a.Children = new List<NodeA>();
    
        foreach (NodeB child in b.Children)
        {
            a.Children.Add((NodeA)child);
        }
    }