{"record":{"id":"7392a8e4e1dede58","repo":"TheAlgorithms/C-Sharp","slug":"feature-vectors-must-be-of-the-same-length","errorCode":null,"errorMessage":"Feature vectors must be of the same length.","messagePattern":"Feature vectors must be of the same length\\.","errorType":"exception","errorClass":"ArgumentException","httpStatus":null,"severity":"error","filePath":"Algorithms/MachineLearning/KNearestNeighbors.cs","lineNumber":45,"sourceCode":"        {\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        }\n\n        double sum = 0;\n        for (int i = 0; i < a.Length; i++)\n        {\n            double diff = a[i] - b[i];\n            sum += diff * diff;\n        }\n\n        return Math.Sqrt(sum);\n    }\n\n    /// <summary>\n    /// Adds a training sample to the classifier.\n    /// </summary>\n    /// <param name=\"features\">Feature vector of the sample.</param>\n    /// <param name=\"label\">Label of the sample.</param>\n    public void AddSample(double[] features, TLabel label)","sourceCodeStart":27,"sourceCodeEnd":63,"githubUrl":"https://github.com/TheAlgorithms/C-Sharp/blob/96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c/Algorithms/MachineLearning/KNearestNeighbors.cs#L27-L63","documentation":"EuclideanDistance requires both feature vectors to have the same number of dimensions; it subtracts element-wise, which is only defined for equal-length arrays. The library throws ArgumentException when a.Length != b.Length instead of producing a wrong or IndexOutOfRange result.","triggerScenarios":"Calling EuclideanDistance(a, b) (directly or via Predict, which compares the query vector against every stored training sample) with arrays of different lengths.","commonSituations":"Training samples added with a different feature count than the prediction input; schema changes adding/removing a feature; a malformed CSV row yielding fewer columns; accidentally passing a label or bias term inside one of the arrays.","solutions":["Ensure every training sample added via AddSample has the same length as the vector passed to Predict.","Validate/normalize input feature vectors to a fixed dimension before calling Predict.","If using EuclideanDistance directly, check a.Length == b.Length before calling."],"exampleFix":"// before\nknn.AddSample(new double[] { 1, 2, 3 }, \"a\");\nknn.Predict(new double[] { 1, 2 }); // length mismatch\n// after\nknn.AddSample(new double[] { 1, 2, 3 }, \"a\");\nknn.Predict(new double[] { 1, 2, 0 }); // same dimensionality","handlingStrategy":"validation","validationCode":"if (query.Length != trainingFeatureLength)\n    throw new ArgumentException($\"Expected {trainingFeatureLength} features, got {query.Length}.\");\nvar label = knn.Predict(query);","typeGuard":"static bool IsValidFeatureVector(double[]? v, int expectedDim) =>\n    v != null && v.Length == expectedDim;","tryCatchPattern":"try\n{\n    var label = knn.Predict(query);\n}\ncatch (ArgumentException ex)\n{\n    // dimension mismatch between query and training vectors\n    logger.LogError(ex, \"Feature dimension mismatch\");\n}","preventionTips":["Define a single FEATURE_DIM constant and validate every vector at the data-ingestion boundary.","Build training and query vectors with the same extraction pipeline.","Validate CSV/JSON row column counts at load time, before adding samples."],"tags":["csharp","machine-learning","dimension-mismatch","feature-vectors"],"backgroundTag":"shape-mismatch","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"}