TheAlgorithms/C-Sharp · error · InvalidOperationException

Vertex does not belong to graph

Error message

Vertex does not belong to graph: {vertex}.

What it means

ThrowIfVertexNotInGraph verifies vertex.Graph == this before any graph operation (AddEdge, RemoveVertex, RemoveEdge, GetNeighbors, AreAdjacent) and throws InvalidOperationException if the Vertex instance belongs to a different graph (or none). Vertices are graph-bound objects, not plain values.

Solutions

  1. Always obtain vertices via the target graph's AddVertex return value.
  2. Verify vertex.Graph == graph before operating, or re-add the vertex to the intended graph.
  3. Catch InvalidOperationException to detect cross-graph misuse in generic code.

Example fix

// before
var v = new Vertex<string>("a");
graph.AddEdge(v, other, 1.0); // throws: v belongs to no graph
// after
var v = graph.AddVertex("a");
graph.AddEdge(v, other, 1.0);
Defensive patterns

Strategy: validation

Validate before calling

static bool BelongsToGraph<T>(Vertex<T> v, DirectedWeightedGraph<T> g) => ReferenceEquals(v.Graph, g);
// call: if (!BelongsToGraph(v, graph)) v = graph.AddVertex(v.Value);

Type guard

static bool IsInGraph<T>(Vertex<T> v, DirectedWeightedGraph<T> g) => ReferenceEquals(v?.Graph, g);

Try / catch

try { graph.AddEdge(u, v, w); }
catch (InvalidOperationException ex) when (ex.Message.StartsWith("Vertex does not belong to graph")) { /* re-add vertices to this graph */ }

Prevention

When it happens

Trigger: Manually constructed new Vertex<T>(...) passed to graph methods, or using a vertex from graphA with graphB: graphB.AddEdge(vertexFromA, other, w).

Common situations: Copying vertices between graphs, caching Vertex instances across graph rebuilds, deserializing vertices without re-attaching them to the target graph.

Understand the failure class

Background: "Invalid state transition" errors: "status must be X, actually Y", "already rejected/charging/uninstalled", "cannot ... while running" — what they mean when a library rejects your call — this error's family across 31 libraries.

Related errors


AI-assisted analysis of TheAlgorithms/C-Sharp@96e2905cab (2026-09-13). Data as JSON: /api/errors/37f286c92018083b. Report an issue: GitHub.

Appendix: source

Thrown at DataStructures/Graph/DirectedWeightedGraph.cs:230

        if (!currentEdgeWeight.Equals(0.0d))
        {
            throw new InvalidOperationException($"Vertex already exists: {currentEdgeWeight}");
        }
    }

    private void ThrowIfOverflow()
    {
        if (Count == capacity)
        {
            throw new InvalidOperationException("Graph overflow.");
        }
    }

    private void ThrowIfVertexNotInGraph(Vertex<T> vertex)
    {
        if (vertex.Graph != this)
        {
            throw new InvalidOperationException($"Vertex does not belong to graph: {vertex}.");
        }
    }
}

View on GitHub (pinned to 96e2905cab)