Reputation: 29244
Consider this declaration with 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 class Node
from outside the base class? I have used this pattern before, but always leaving the derived classes outside of 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
Have I created an un-instantiable class? Can it be initialized via reflection?
Upvotes: 4
Views: 243
Reputation: 180777
Add a static factory method:
public static Node Create<T>()
{
return // your new Node
}
And call it thusly:
var foo = BaseNode<Node>.Create<Node>();
Upvotes: 1
Reputation: 43743
You can instantiate that monster. All you have to do is create your own class that inherits from Node
:
public class MyNode : BaseNode<MyNode>.Node
{
}
Then you can instantiate it like this:
BaseNode<MyNode> obj = new BaseNode<MyNode>();
Why you would want to do this, though, is a different matter entirely...
Upvotes: 5