TheAlgorithms/C-Sharp · error · ArgumentException

Strings must be equal length.

Error message

Strings must be equal length.

What it means

HammingDistance.Calculate computes the number of positions at which two strings differ, which is only defined for equal-length strings. It throws ArgumentException when s1.Length != s2.Length. Unlike Levenshtein distance, Hamming distance has no meaning for strings of different lengths, hence the strict check.

Solutions

  1. Validate lengths at the call site: if (s1.Length != s2.Length) handle or pad before calling.
  2. Use a Levenshtein/Jaccard similarity implementation instead when lengths may differ.
  3. Normalize both strings (trim, pad, or truncate to a fixed length) before comparison.
  4. Catch ArgumentException and report the mismatch to the user.

Example fix

// before
var d = HammingDistance.Calculate(a, b); // lengths may differ
// after
var d = a.Length == b.Length
    ? HammingDistance.Calculate(a, b)
    : LevenshteinDistance.Calculate(a, b);
Defensive patterns

Strategy: validation

Validate before calling

if (s1.Length != s2.Length)
{
    // fall back to Levenshtein or report a length mismatch to the user
}

Try / catch

try
{
    distance = HammingDistance.Calculate(s1, s2);
}
catch (ArgumentException ex) when (ex.Message.Contains("equal length"))
{
    distance = LevenshteinDistance.Calculate(s1, s2); // or handle mismatch
}

Prevention

When it happens

Trigger: Calling Calculate("karolin", "kathrinX") or any pair of strings with differing Length; strings that differ only after trimming or newline handling.

Common situations: Comparing DNA/byte sequences where one was truncated; user inputs of different lengths; confusing HammingDistance with LevenshteinDistance (which accepts unequal lengths).

Understand the failure class

Background: "Must be a positive integer", "Invalid value", "Unsupported": the invalid-argument-value error family, when a library rejects the value you pass — this error's family across 35 libraries.

Related errors


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

Appendix: source

Thrown at Algorithms/Strings/Similarity/HammingDistance.cs:24

///         Time complexity is O(n) where n is the length of the string.
///     </para>
///     <para>
///         Wikipedia: https://en.wikipedia.org/wiki/Hamming_distance.
///     </para>
/// </summary>
public static class HammingDistance
{
    /// <summary>
    ///     Calculates Hamming distance between two strings of equal length.
    /// </summary>
    /// <param name="s1">First string.</param>
    /// <param name="s2">Second string.</param>
    /// <returns>Levenshtein distance between source and target strings.</returns>
    public static int Calculate(string s1, string s2)
    {
        if (s1.Length != s2.Length)
        {
            throw new ArgumentException("Strings must be equal length.");
        }

        var distance = 0;
        for (var i = 0; i < s1.Length; i++)
        {
            distance += s1[i] != s2[i] ? 1 : 0;
        }

        return distance;
    }
}

View on GitHub (pinned to 96e2905cab)