{"record":{"id":"8956540fc86fbc92","repo":"TheAlgorithms/C-Sharp","slug":"argumentnullexception-features","errorCode":null,"errorMessage":"ArgumentNullException: features","messagePattern":"ArgumentNullException: features","errorType":"exception","errorClass":"ArgumentNullException","httpStatus":null,"severity":"error","filePath":"Algorithms/MachineLearning/KNearestNeighbors.cs","lineNumber":67,"sourceCode":"        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)\n    {\n        if (features == null)\n        {\n            throw new ArgumentNullException(nameof(features));\n        }\n\n        trainingData.Add((features, label));\n    }\n\n    /// <summary>\n    /// Predicts the label for a given feature vector using the KNN algorithm.\n    /// </summary>\n    /// <param name=\"features\">Feature vector to classify.</param>\n    /// <returns>Predicted label.</returns>\n    /// <exception cref=\"InvalidOperationException\">Thrown if there is no training data.</exception>\n    public TLabel Predict(double[] features)\n    {\n        if (trainingData.Count == 0)\n        {\n            throw new InvalidOperationException(\"No training data available.\");\n        }\n","sourceCodeStart":49,"sourceCodeEnd":85,"githubUrl":"https://github.com/TheAlgorithms/C-Sharp/blob/96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c/Algorithms/MachineLearning/KNearestNeighbors.cs#L49-L85","documentation":"This ArgumentNullException is a defensive guard in AddSample (KNearestNeighbors.cs:67): the caller passed a null feature array when registering a training sample. A null feature vector cannot participate in distance computation, so the classifier rejects it immediately rather than failing later inside Predict. It fires whenever AddSample(double[] features, TLabel label) is invoked with features == null.","triggerScenarios":"Calling AddSample(null, someLabel), or passing a features array that is null because it came from a failed parse or an unpopulated record.","commonSituations":"Loading a training dataset from CSV/JSON where a row's feature fields failed to parse; mapping pipeline producing null for missing rows; refactoring where the features variable was never assigned.","solutions":["Pass a valid non-null double[] feature vector for every training sample.","Filter out null entries when bulk-loading training data before calling AddSample.","Guard each row during data loading and log/skip malformed records instead of adding them."],"exampleFix":"// before\nknn.AddSample(row.Features, row.Label); // Features may be null\n// after\nif (row.Features != null)\n{\n    knn.AddSample(row.Features, row.Label);\n}","handlingStrategy":"type-guard","validationCode":"if (features == null || features.Length == 0)\n    throw new ArgumentException(\"Sample features must be a non-empty array.\");\nknn.AddSample(features, label);","typeGuard":"static bool IsUsableSample(double[]? features) => features != null && features.Length > 0;","tryCatchPattern":"try\n{\n    knn.AddSample(features, label);\n}\ncatch (ArgumentNullException ex)\n{\n    // ex.ParamName == \"features\": skip/log the malformed sample\n    logger.LogWarning(\"Skipped training sample with null features: {Label}\", label);\n}","preventionTips":["Filter null-featured records when bulk-loading training data.","Make the data loader fail loudly (or skip with a log) on rows that produce null features.","Never cache double[]? in variables intended as training samples."],"tags":["csharp","null-argument","machine-learning","training-data"],"backgroundTag":"null-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"}