{"record":{"id":"44e87326d7d64609","repo":"TheAlgorithms/C-Sharp","slug":"strings-must-be-equal-length","errorCode":null,"errorMessage":"Strings must be equal length.","messagePattern":"Strings must be equal length\\.","errorType":"validation","errorClass":"ArgumentException","httpStatus":null,"severity":"error","filePath":"Algorithms/Strings/Similarity/HammingDistance.cs","lineNumber":24,"sourceCode":"///         Time complexity is O(n) where n is the length of the string.\n///     </para>\n///     <para>\n///         Wikipedia: https://en.wikipedia.org/wiki/Hamming_distance.\n///     </para>\n/// </summary>\npublic static class HammingDistance\n{\n    /// <summary>\n    ///     Calculates Hamming distance between two strings of equal length.\n    /// </summary>\n    /// <param name=\"s1\">First string.</param>\n    /// <param name=\"s2\">Second string.</param>\n    /// <returns>Levenshtein distance between source and target strings.</returns>\n    public static int Calculate(string s1, string s2)\n    {\n        if (s1.Length != s2.Length)\n        {\n            throw new ArgumentException(\"Strings must be equal length.\");\n        }\n\n        var distance = 0;\n        for (var i = 0; i < s1.Length; i++)\n        {\n            distance += s1[i] != s2[i] ? 1 : 0;\n        }\n\n        return distance;\n    }\n}\n","sourceCodeStart":6,"sourceCodeEnd":36,"githubUrl":"https://github.com/TheAlgorithms/C-Sharp/blob/96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c/Algorithms/Strings/Similarity/HammingDistance.cs#L6-L36","documentation":"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.","triggerScenarios":"Calling Calculate(\"karolin\", \"kathrinX\") or any pair of strings with differing Length; strings that differ only after trimming or newline handling.","commonSituations":"Comparing DNA/byte sequences where one was truncated; user inputs of different lengths; confusing HammingDistance with LevenshteinDistance (which accepts unequal lengths).","solutions":["Validate lengths at the call site: if (s1.Length != s2.Length) handle or pad before calling.","Use a Levenshtein/Jaccard similarity implementation instead when lengths may differ.","Normalize both strings (trim, pad, or truncate to a fixed length) before comparison.","Catch ArgumentException and report the mismatch to the user."],"exampleFix":"// before\nvar d = HammingDistance.Calculate(a, b); // lengths may differ\n// after\nvar d = a.Length == b.Length\n    ? HammingDistance.Calculate(a, b)\n    : LevenshteinDistance.Calculate(a, b);","handlingStrategy":"validation","validationCode":"if (s1.Length != s2.Length)\n{\n    // fall back to Levenshtein or report a length mismatch to the user\n}","typeGuard":null,"tryCatchPattern":"try\n{\n    distance = HammingDistance.Calculate(s1, s2);\n}\ncatch (ArgumentException ex) when (ex.Message.Contains(\"equal length\"))\n{\n    distance = LevenshteinDistance.Calculate(s1, s2); // or handle mismatch\n}","preventionTips":["Only use Hamming distance when inputs are guaranteed same-length (fixed codes, DNA k-mers).","Normalize inputs (trim/pad/truncate) to equal length before comparison.","Prefer edit distance when lengths can vary.","Test with unequal-length inputs to confirm guard behavior."],"tags":["invalid-argument-value","hamming-distance","csharp","string-comparison"],"backgroundTag":"invalid-argument-value","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"}