Yesterday, I was explaining C#\'s generic constraints to my friends. When demonstrating the where T : CLASSNAME
constraint, I whipped up something like this:
This approach is widely used in Trees and other Graph-like structures. Here you say to compiler, that T has API of UnusableClass. That said, you can implement TreeNode as follows:
public class TreeNode
where T:TreeNode
{
public T This { get { return this as T;} }
public T Parent { get; set; }
public List Childrens { get; set; }
public virtual void AddChild(T child)
{
Childrens.Add(child);
child.Parent = This;
}
public virtual void SetParent(T parent)
{
parent.Childrens.Add(This);
Parent = parent;
}
}
And then use it like this:
public class BinaryTree:TreeNode
{
}