TheAlgorithms/C-Sharp · error · ArgumentNullException

ArgumentNullException: features

Error message

ArgumentNullException: features

What it means

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.

Solutions

  1. Pass a valid non-null double[] feature vector for every training sample.
  2. Filter out null entries when bulk-loading training data before calling AddSample.
  3. Guard each row during data loading and log/skip malformed records instead of adding them.

Example fix

// before
knn.AddSample(row.Features, row.Label); // Features may be null
// after
if (row.Features != null)
{
    knn.AddSample(row.Features, row.Label);
}
Defensive patterns

Strategy: type-guard

Validate before calling

if (features == null || features.Length == 0)
    throw new ArgumentException("Sample features must be a non-empty array.");
knn.AddSample(features, label);

Type guard

static bool IsUsableSample(double[]? features) => features != null && features.Length > 0;

Try / catch

try
{
    knn.AddSample(features, label);
}
catch (ArgumentNullException ex)
{
    // ex.ParamName == "features": skip/log the malformed sample
    logger.LogWarning("Skipped training sample with null features: {Label}", label);
}

Prevention

When it happens

Trigger: Calling AddSample(null, someLabel), or passing a features array that is null because it came from a failed parse or an unpopulated record.

Common situations: 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.

Related errors


AI-assisted analysis of TheAlgorithms/C-Sharp@96e2905cab (2026-09-13). Data as JSON: /api/errors/8956540fc86fbc92. Report an issue: GitHub.

Appendix: source

Thrown at Algorithms/MachineLearning/KNearestNeighbors.cs:67

        for (int i = 0; i < a.Length; i++)
        {
            double diff = a[i] - b[i];
            sum += diff * diff;
        }

        return Math.Sqrt(sum);
    }

    /// <summary>
    /// Adds a training sample to the classifier.
    /// </summary>
    /// <param name="features">Feature vector of the sample.</param>
    /// <param name="label">Label of the sample.</param>
    public void AddSample(double[] features, TLabel label)
    {
        if (features == null)
        {
            throw new ArgumentNullException(nameof(features));
        }

        trainingData.Add((features, label));
    }

    /// <summary>
    /// Predicts the label for a given feature vector using the KNN algorithm.
    /// </summary>
    /// <param name="features">Feature vector to classify.</param>
    /// <returns>Predicted label.</returns>
    /// <exception cref="InvalidOperationException">Thrown if there is no training data.</exception>
    public TLabel Predict(double[] features)
    {
        if (trainingData.Count == 0)
        {
            throw new InvalidOperationException("No training data available.");
        }

View on GitHub (pinned to 96e2905cab)