Search code examples
c#genericsneo4jneo4jclient

Using C# generic class with Neo4jClient


I would like to create a generic class that creates nodes for multiple node class types. See example below:

public NodeReference<TObject> CreateObject(TObject objectType)
        {  
            NodeReference<TObject> nodeReference = 0;
            nodeReference = clientConnection.Create<TObject> (objectType);
            return nodeReference;
        }

However I keep getting the following error enter image description here


Solution

  • You can define your method like so:

    public NodeReference<TObject> CreateObject(TObject objectType)
        where TObject: class //<-- NEW BIT HERE
    {  
        NodeReference<TObject> nodeReference = 0;
        nodeReference = clientConnection.Create<TObject> (objectType);
        return nodeReference;
    }
    

    by putting where TObject: class you are saying that the type of 'TObject' must always be a class (or reference type). You may need to also put:

    where TObject: class, new()
    

    but I can't remember - the new() bit means that the class has to have a constructor with no arguments (which can be the default constructor).