{"record":{"id":"8bd997d4b305cabf","repo":"TheAlgorithms/C-Sharp","slug":"specified-argument-was-out-of-the-range-of-valid-values","errorCode":null,"errorMessage":"Specified argument was out of the range of valid values. (Parameter 'start')","messagePattern":"Specified argument was out of the range of valid values\\. \\(Parameter 'start'\\)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"Algorithms/Problems/TravelingSalesman/TravelingSalesmanSolver.cs","lineNumber":77,"sourceCode":"\n    /// <summary>\n    /// Solves the TSP using the nearest neighbor heuristic. This method builds a route by always visiting the nearest unvisited city next.\n    /// This approach is much faster but may not find the optimal solution.\n    /// </summary>\n    /// <param name=\"distanceMatrix\">A square matrix where element [i, j] represents the distance from city i to city j.</param>\n    /// <param name=\"start\">The starting city index.</param>\n    /// <returns>A tuple containing the route (as an array of city indices) and the total distance.</returns>\n    public static (int[] Route, double Distance) SolveNearestNeighbor(double[,] distanceMatrix, int start = 0)\n    {\n        int n = distanceMatrix.GetLength(0);\n        if (n != distanceMatrix.GetLength(1))\n        {\n            throw new ArgumentException(\"Distance matrix must be square.\");\n        }\n\n        if (start < 0 || start >= n)\n        {\n            throw new ArgumentOutOfRangeException(nameof(start));\n        }\n\n        var visited = new bool[n];\n        List<int> route = [start];\n        visited[start] = true;\n        double totalDistance = 0;\n        int current = start;\n        for (int step = 1; step < n; step++)\n        {\n            double minDist = double.MaxValue;\n            int next = -1;\n            for (int j = 0; j < n; j++)\n            {\n                if (!visited[j] && distanceMatrix[current, j] < minDist)\n                {\n                    minDist = distanceMatrix[current, j];\n                    next = j;\n                }","sourceCodeStart":59,"sourceCodeEnd":95,"githubUrl":"https://github.com/TheAlgorithms/C-Sharp/blob/96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c/Algorithms/Problems/TravelingSalesman/TravelingSalesmanSolver.cs#L59-L95","documentation":"SolveNearestNeighbor throws ArgumentOutOfRangeException when the start index is negative or >= n, since it must index into the matrix as the tour's starting city. Note the check happens after the square-matrix validation, using n = rows.","triggerScenarios":"Calling SolveNearestNeighbor(matrix, start) with start < 0 or start >= matrix dimension, e.g. SolveNearestNeighbor(m, 5) on a 4-city matrix or start defaulted from a bad config.","commonSituations":"Hardcoded start index kept after shrinking the dataset; 1-based city IDs passed instead of 0-based indices; start read from user input without bounds checking.","solutions":["Pass a start index in [0, n-1]; convert 1-based IDs with start - 1.","Clamp or validate start before calling.","Fix the source (config/UI) that supplied the out-of-range start."],"exampleFix":"// before\nsolver.SolveNearestNeighbor(m, cityId); // 1-based\n// after\nvar r = TravelingSalesmanSolver.SolveNearestNeighbor(m, cityId - 1);","handlingStrategy":"validation","validationCode":"if (start < 0 || start >= m.GetLength(0)) throw new ArgumentOutOfRangeException(nameof(start), start, \"Start must index a city\");","typeGuard":null,"tryCatchPattern":"try { var r = TravelingSalesmanSolver.SolveNearestNeighbor(m, start); }\ncatch (ArgumentOutOfRangeException ex) { logger.LogError(ex, \"Invalid start city\"); }","preventionTips":["Convert 1-based user IDs to 0-based indices at the boundary","Re-validate cached start indices after dataset changes","Clamp start with Math.Clamp(start, 0, n - 1) when appropriate"],"tags":["argument-validation","csharp","tsp"],"backgroundTag":"argument-out-of-range","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"}