TheAlgorithms/C-Sharp · error · InvalidOperationException

Graph capacity should always be a non-negative integer.

Error message

Graph capacity should always be a non-negative integer.

What it means

DirectedWeightedGraph validates the requested capacity at construction/growth time and throws InvalidOperationException when capacity is negative. The library requires capacity to be a non-negative integer because it sizes internal vertex storage from it. A negative value is always a caller bug (bad config or arithmetic), not a recoverable state.

Solutions

  1. Pass a positive integer capacity, e.g. new DirectedWeightedGraph<T>(100).
  2. Clamp or validate the value before constructing: if (capacity < 0) capacity = DefaultCapacity;
  3. Fix the arithmetic/source of the negative number (check subtraction order and parsed values).

Example fix

// before
var graph = new DirectedWeightedGraph<string>(maxSize - alreadyUsed); // throws when alreadyUsed > maxSize
// after
var capacity = Math.Max(0, maxSize - alreadyUsed);
var graph = new DirectedWeightedGraph<string>(capacity);
Defensive patterns

Strategy: validation

Validate before calling

static bool IsValidGraphCapacity(int capacity) => capacity >= 0;
// call: if (!IsValidGraphCapacity(n)) throw new ArgumentOutOfRangeException(nameof(n));

Type guard

static bool IsNonNegative(int v) => v >= 0;

Try / catch

try { var g = new DirectedWeightedGraph<T>(cap); }
catch (InvalidOperationException ex) when (ex.Message.Contains("non-negative")) { /* fall back to default capacity */ }

Prevention

When it happens

Trigger: new DirectedWeightedGraph<T>(-1) or any constructor/resize path where a negative capacity int is passed to ThrowIfNegativeCapacity.

Common situations: Computing capacity from user input or constants with a sign error (e.g. maxSize - used when used > maxSize), passing -1 as a 'default/unlimited' sentinel, or parsing config values that allowed negatives.

Understand the failure class

Background: "Must be a positive integer", "Invalid value", "Unsupported": the invalid-argument-value error family, when a library rejects the value you pass — this error's family across 35 libraries.

Related errors


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

Appendix: source

Thrown at DataStructures/Graph/DirectedWeightedGraph.cs:198

    /// </summary>
    /// <param name="startVertex">first vertex in edge.</param>
    /// <param name="endVertex">secnod vertex in edge.</param>
    /// <returns>distance between the two.</returns>
    public double AdjacentDistance(Vertex<T> startVertex, Vertex<T> endVertex)
    {
        if (AreAdjacent(startVertex, endVertex))
        {
            return adjacencyMatrix[startVertex.Index, endVertex.Index];
        }

        return 0;
    }

    private static void ThrowIfNegativeCapacity(int capacity)
    {
        if (capacity < 0)
        {
            throw new InvalidOperationException("Graph capacity should always be a non-negative integer.");
        }
    }

    private static void ThrowIfWeightZero(double weight)
    {
        if (weight.Equals(0.0d))
        {
            throw new InvalidOperationException("Edge weight cannot be zero.");
        }
    }

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

View on GitHub (pinned to 96e2905cab)