How can I instantiate this class?

Consider this ad using generics:

public class BaseNode<TNode> where TNode : BaseNode<TNode> { public class Node : BaseNode<Node> { public Node() { } } } 

Is there a way to create an instance of a Node class from outside the base class? I have used this template before, but always leave the derived classes outside the base class.

How do you write the following without a compiler error?

 var obj = new BaseNode<Node>.Node(); // error CS0246: The type or namespace name 'Node' could not be found 

Did I create a non replicable class? Can it be initialized with reflection?

+4
source share
2 answers

You can create an instance of this monster. All you have to do is create your own class that inherits from Node :

 public class MyNode : BaseNode<MyNode>.Node { } 

Then you can create it as follows:

 BaseNode<MyNode> obj = new BaseNode<MyNode>(); 

Why would you like to do this, however, this is a completely different matter ...

+5
source

Add a static factory method:

 public static Node Create<T>() { return // your new Node } 

And call it that:

 var foo = BaseNode<Node>.Create<Node>(); 
+1
source

All Articles