{"record":{"id":"2f920ac39979ae83","repo":"TheAlgorithms/C-Sharp","slug":"k-must-be-at-least-1","errorCode":null,"errorMessage":"k must be at least 1.","messagePattern":"k must be at least 1\\.","errorType":"exception","errorClass":"ArgumentOutOfRangeException","httpStatus":null,"severity":"error","filePath":"Algorithms/MachineLearning/KNearestNeighbors.cs","lineNumber":28,"sourceCode":"/// </summary>\n/// <typeparam name=\"TLabel\">\n/// The type of the label used for classification. This can be any type that represents the class or category of a sample.\n/// </typeparam>\npublic class KNearestNeighbors<TLabel>\n{\n    private readonly List<(double[] Features, TLabel Label)> trainingData = new();\n    private readonly int k;\n\n    /// <summary>\n    /// Initializes a new instance of the <see cref=\"KNearestNeighbors{TLabel}\"/> classifier.\n    /// </summary>\n    /// <param name=\"k\">Number of neighbors to consider for classification.</param>\n    /// <exception cref=\"ArgumentOutOfRangeException\">Thrown if k is less than 1.</exception>\n    public KNearestNeighbors(int k)\n    {\n        if (k < 1)\n        {\n            throw new ArgumentOutOfRangeException(nameof(k), \"k must be at least 1.\");\n        }\n\n        this.k = k;\n    }\n\n    /// <summary>\n    /// Calculates the Euclidean distance between two feature vectors.\n    /// </summary>\n    /// <param name=\"a\">First feature vector.</param>\n    /// <param name=\"b\">Second feature vector.</param>\n    /// <returns>Euclidean distance.</returns>\n    /// <exception cref=\"ArgumentException\">Thrown if vectors are of different lengths.</exception>\n    public static double EuclideanDistance(double[] a, double[] b)\n    {\n        if (a.Length != b.Length)\n        {\n            throw new ArgumentException(\"Feature vectors must be of the same length.\");\n        }","sourceCodeStart":10,"sourceCodeEnd":46,"githubUrl":"https://github.com/TheAlgorithms/C-Sharp/blob/96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c/Algorithms/MachineLearning/KNearestNeighbors.cs#L10-L46","documentation":"The KNearestNeighbors constructor rejects a neighbor count k below 1. k controls how many nearest training samples vote on a classification, so k < 1 is meaningless and would break the top-k selection in Predict. The library throws ArgumentOutOfRangeException at construction time to fail fast.","triggerScenarios":"Calling new KNearestNeighbors(0), new KNearestNeighbors(-1), or any k derived from a computation/user input that resolves to less than 1.","commonSituations":"k read from a config file or CLI defaulting to 0 when unset; computing k as a fraction of dataset size with integer division rounding down to 0 on tiny datasets; off-by-one loops generating k = 0.","solutions":["Pass k >= 1 to the constructor (k = 1 is valid for nearest-neighbor).","Clamp or validate user/config-supplied k before constructing: Math.Max(1, configuredK).","Check any computed k (e.g. dataset.Count / someFactor) for rounding down to 0 and enforce a minimum of 1."],"exampleFix":"// before\nint k = samples.Count / 10; // can be 0 for small datasets\nvar knn = new KNearestNeighbors(k);\n// after\nint k = Math.Max(1, samples.Count / 10);\nvar knn = new KNearestNeighbors(k);","handlingStrategy":"validation","validationCode":"if (k < 1)\n    throw new ArgumentException(\"k must be at least 1 before constructing KNearestNeighbors.\");\nvar knn = new KNearestNeighbors(k);","typeGuard":null,"tryCatchPattern":"try\n{\n    var knn = new KNearestNeighbors(k);\n}\ncatch (ArgumentOutOfRangeException ex)\n{\n    // ex.ParamName == \"k\": fall back to a sane default\n    var knn = new KNearestNeighbors(3);\n}","preventionTips":["Never take k directly from unvalidated user/config input; clamp with Math.Max(1, k).","When deriving k from dataset size, guard against integer division rounding to 0.","Common convention: use odd k (e.g. 3, 5) to reduce tie votes."],"tags":["csharp","argument-out-of-range","machine-learning","constructor","validation"],"backgroundTag":"invalid-constructor-argument","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"}