0

Is there a way to implement the "CreateNode" method in my library abstract below? Or can this only be done in client code outside the library? I current get the error "Cannot create an instance of the abstract class or interface 'ToplogyLibrary.AbstractNode"

public abstract class AbstractTopology<T>
{
    // Properties
    public Dictionary<T, AbstractNode<T>> Nodes { get; private set; }
    public List<AbstractRelationship<T>> Relationships { get; private set; }

    // Constructors
    protected AbstractTopology()
    {
        Nodes = new Dictionary<T, AbstractNode<T>>();
    }

    // Methods
    public AbstractNode<T> CreateNode()
    {
        var node = new AbstractNode<T>();  // ** Does not work **
        Nodes.Add(node.Key, node);
        }
    }
 }

    public abstract class AbstractNode<T>
    {
        public T Key { get; set; }
    }

    public abstract class AbstractRelationship<T>
    {
        public AbstractNode<T> Parent { get; set; }
        public AbstractNode<T> Child { get; set; }

    }

3 Answers 3

3

You cannot create an instance of an abstract class, which is why you are receiving the error.

What you could do instead is declare CreateNode as an abstract method, and implement it in any descendant classes.

Sign up to request clarification or add additional context in comments.

1 Comment

dang it, you've got faster fingers.
2

Well what concrete node class do you want to be created? Is this perhaps something which should be left up to the concrete topology class? If so, you might want to make it abstract:

public abstract AbstractNode<T> CreateNode();

Then provide a concrete implementation in the concrete topology class.

Alternatively, you could make your class generic in the node type as well:

public abstract class AbstractTopology<TValue, TNode>
    where TNode : AbstractNode<TValue>, new()

Then you could implement CreateNode like this:

public AbstractNode<T> CreateNode()
{
    var node = new TNode();
    Nodes.Add(node.Key, node);
    return node;   
}

Personally I get a little suspicious of designs involving this many abstract classes, but perhaps you've got good reasons.

1 Comment

Sounds good. Will the caller using the method have to pass the type when they are using the mehod however?
0

define a protected pure abstract virtual method that CreateNode will call that the subclass return a new object

CreateNodeImpl or something.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.