{"record":{"id":"1bc77f2c2bada747","repo":"TheAlgorithms/C-Sharp","slug":"graph-capacity-should-always-be-a-non-negative-integer","errorCode":null,"errorMessage":"Graph capacity should always be a non-negative integer.","messagePattern":"Graph capacity should always be a non-negative integer\\.","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"DataStructures/Graph/DirectedWeightedGraph.cs","lineNumber":198,"sourceCode":"    /// </summary>\n    /// <param name=\"startVertex\">first vertex in edge.</param>\n    /// <param name=\"endVertex\">secnod vertex in edge.</param>\n    /// <returns>distance between the two.</returns>\n    public double AdjacentDistance(Vertex<T> startVertex, Vertex<T> endVertex)\n    {\n        if (AreAdjacent(startVertex, endVertex))\n        {\n            return adjacencyMatrix[startVertex.Index, endVertex.Index];\n        }\n\n        return 0;\n    }\n\n    private static void ThrowIfNegativeCapacity(int capacity)\n    {\n        if (capacity < 0)\n        {\n            throw new InvalidOperationException(\"Graph capacity should always be a non-negative integer.\");\n        }\n    }\n\n    private static void ThrowIfWeightZero(double weight)\n    {\n        if (weight.Equals(0.0d))\n        {\n            throw new InvalidOperationException(\"Edge weight cannot be zero.\");\n        }\n    }\n\n    private static void ThrowIfEdgeExists(double currentEdgeWeight)\n    {\n        if (!currentEdgeWeight.Equals(0.0d))\n        {\n            throw new InvalidOperationException($\"Vertex already exists: {currentEdgeWeight}\");\n        }\n    }","sourceCodeStart":180,"sourceCodeEnd":216,"githubUrl":"https://github.com/TheAlgorithms/C-Sharp/blob/96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c/DataStructures/Graph/DirectedWeightedGraph.cs#L180-L216","documentation":"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.","triggerScenarios":"new DirectedWeightedGraph<T>(-1) or any constructor/resize path where a negative capacity int is passed to ThrowIfNegativeCapacity.","commonSituations":"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.","solutions":["Pass a positive integer capacity, e.g. new DirectedWeightedGraph<T>(100).","Clamp or validate the value before constructing: if (capacity < 0) capacity = DefaultCapacity;","Fix the arithmetic/source of the negative number (check subtraction order and parsed values)."],"exampleFix":"// before\nvar graph = new DirectedWeightedGraph<string>(maxSize - alreadyUsed); // throws when alreadyUsed > maxSize\n// after\nvar capacity = Math.Max(0, maxSize - alreadyUsed);\nvar graph = new DirectedWeightedGraph<string>(capacity);","handlingStrategy":"validation","validationCode":"static bool IsValidGraphCapacity(int capacity) => capacity >= 0;\n// call: if (!IsValidGraphCapacity(n)) throw new ArgumentOutOfRangeException(nameof(n));","typeGuard":"static bool IsNonNegative(int v) => v >= 0;","tryCatchPattern":"try { var g = new DirectedWeightedGraph<T>(cap); }\ncatch (InvalidOperationException ex) when (ex.Message.Contains(\"non-negative\")) { /* fall back to default capacity */ }","preventionTips":["Never use -1 as a sentinel for 'unlimited' capacity.","Clamp computed capacities with Math.Max(0, value).","Validate config-sourced sizes at load time."],"tags":["csharp","data-structures","graph","argument-validation"],"backgroundTag":"invalid-argument-value","analyzedSha":"96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c","analyzedAt":"2026-09-13T17:04:01.438Z","contentChangedAt":"2026-09-13T17:04:01.438Z","schemaVersion":2},"datasetVersion":"2026-09-16T04:17:20.429Z"}