RSS 2.0
Sign In
# Wednesday, February 11, 2009

Could you think of a C# method accepting an ancestor, and forbidding a descendant of a class at compile time?

The answer to this probably is: why do you need such a reptile.

Well, I don't. I didn't meant to create such a method, but generics help a lot!

public class BinaryTreeNode<Node>
  where Node: BinaryTreeNode<Node>
  public Node parent;
  public Node left;
  public Node right;

public class MyNode: BinaryTreeNode<MyNode>
  public int key;

public class MyRoot: MyNode

public class Test
  public void test()
    MyRoot root = new MyRoot();

    // print((MyNode)root); // This works.
    print(root); // This does not work.

  private static void print<T>(T node)
    where T: BinaryTreeNode<T>
    Console.WriteLine("print me");

By the way, BinaryTreeNode is an "abstract" class, as you cannot instantiate it but inherit only.

Wednesday, February 11, 2009 1:59:17 PM UTC  #    Comments [0] -
Incremental Parser | Tips and tricks
All comments require the approval of the site owner before being displayed.
Home page

Comment (Some html is allowed: a@href@title, b, blockquote@cite, em, i, strike, strong, sub, super, u) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

[Captcha]Enter the code shown (prevents robots):

Live Comment Preview
<July 2024>
Total Posts: 387
This Year: 3
This Month: 0
This Week: 0
Comments: 1371
Locations of visitors to this page
The opinions expressed herein are our own personal opinions and do not represent our employer's view in anyway.

© 2024, Nesterovsky bros
All Content © 2024, Nesterovsky bros
DasBlog theme 'Business' created by Christoph De Baene (delarou)