0

How can I refactor this code?

class Node
{
   public Node Parent { get; set; }
}

class AVLNode
{
   public AVLNode Parent { get; set; }
}

I tried to use inheritance, but then I have to use type casting:

class AVLNode : Node
{
}

class Program
{
   void Main()
   {
      AVLNode a = new AVLNode();
      AVLNode b = a.Parent **as AVLNode**;
   }
}
  • 2
    What refactoring are you trying to perform? – Joshua Smith Jun 19 '13 at 23:50
7

Try creating a generic interface (INode<out T>). You code will change into something like this:

interface INode<out T>
{
  T Parent { get; set; }
}

class Node : INode<Node>
{
  public Node Parent { get; set; }
}

class AVLNode : INode<AVLNode>
{
  public AVLNode Parent { get; set; }
}

Your calling code is simply:

AVLNode a = new AVLNode();
AVLNode b = a.Parent;
  • I'd rename the interface to make it more generic, it's an interface to make objects implement a parent value of its own type (so basicly it has nothing to do with Node). PS: You forgot the Property Names in your code sample! :D – Frederik P. Jun 25 '13 at 7:03
  • D'oh! I do that all the time for some reason, but usually I have Visual Studio to nag me about it. As for the interface, it's open to being fleshed out later with more things that are inherently node-ish. I can't think of any application for this that isn't a node, because having a parent that has a parent turns into a data structure, which means each child is a node. – mgw854 Jun 25 '13 at 13:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.