{"record":{"id":"2958d1e82d100697","repo":"TheAlgorithms/C-Sharp","slug":"the-sequence-may-only-contain-ones-or-zeros","errorCode":null,"errorMessage":"The sequence may only contain ones or zeros","messagePattern":"The sequence may only contain ones or zeros","errorType":"exception","errorClass":"ArgumentException","httpStatus":null,"severity":"error","filePath":"DataStructures/BitArray.cs","lineNumber":769,"sourceCode":"                return false;\n            }\n        }\n\n        return true;\n    }\n\n    /// <summary>\n    ///     Gets has-code of bit-array.\n    ///     Assumes bit-array length must been smaller or equal to 32.\n    /// </summary>\n    /// <returns>hash-code for this BitArray instance.</returns>\n    public override int GetHashCode() => ToInt32();\n\n    private static void ThrowIfSequenceIsInvalid(string sequence)\n    {\n        if (!Match(sequence))\n        {\n            throw new ArgumentException(\"The sequence may only contain ones or zeros\");\n        }\n    }\n\n    /// <summary>\n    ///     Utility method for checking a given sequence contains only zeros and ones.\n    ///     This method will used in Constructor (sequence : string) and Compile(sequence : string).\n    /// </summary>\n    /// <param name=\"sequence\">String sequence.</param>\n    /// <returns>returns True if sequence contains only zeros and ones; False otherwise.</returns>\n    private static bool Match(string sequence) => sequence.All(ch => ch == '0' || ch == '1');\n}\n","sourceCodeStart":751,"sourceCodeEnd":781,"githubUrl":"https://github.com/TheAlgorithms/C-Sharp/blob/96e2905cab7bc6b33ac0a34ee5bb82ddccbcbb6c/DataStructures/BitArray.cs#L751-L781","documentation":"ThrowIfSequenceIsInvalid validates that a binary string sequence contains only '0' and '1' characters (via the Match regex/utility). It is used by the BitArray string constructor and Compile(sequence); any other character makes the sequence unparseable as binary, so an ArgumentException is thrown.","triggerScenarios":"new BitArray(\"10a01\") or Compile(\"12\") — any string passed to the sequence constructor or Compile containing characters other than '0' and '1' (letters, whitespace, '+', '-', punctuation, etc.).","commonSituations":"Reading binary values from user input, config files, or HTTP payloads without sanitizing; copying bit strings with hidden whitespace or BOM characters; accidentally passing decimal strings like \"102\" as binary.","solutions":["Sanitize the input: strip whitespace/underscores and verify every character is '0' or '1' before constructing or calling Compile.","Trim the string and remove formatting characters (spaces, separators) that may have been added for readability.","If the input is decimal/hex, convert it to binary with Convert.ToString(value, 2) instead of passing it as a raw sequence.","Validate with a regex ^[01]+$ and reject or normalize invalid input at the boundary."],"exampleFix":"// before\nvar ba = new BitArray(\"10 01\"); // space -> throws\n\n// after\nvar raw = \"10 01\";\nvar seq = raw.Replace(\" \", \"\");\nif (!System.Text.RegularExpressions.Regex.IsMatch(seq, \"^[01]+$\"))\n    throw new ArgumentException(\"Invalid binary sequence\");\nvar ba = new BitArray(seq);","handlingStrategy":"validation","validationCode":"bool IsValidSequence(string s) => System.Text.RegularExpressions.Regex.IsMatch(s?.Trim() ?? \"\", \"^[01]+$\");","typeGuard":"bool IsBinaryString(string s) => !string.IsNullOrEmpty(s) && s.All(c => c is '0' or '1');","tryCatchPattern":"try { var ba = new BitArray(seq); } catch (ArgumentException ex) when (ex.Message.Contains(\"ones or zeros\")) { /* sanitize and retry or reject input */ }","preventionTips":["Regex-validate ^[01]+$ at every input boundary before constructing.","Trim and strip whitespace/underscores/separators from user or config input.","Convert decimal/hex inputs with Convert.ToString(v, 2) instead of passing raw text.","Log the offending sequence when rejecting input to speed debugging."],"tags":["csharp","data-structures","bitarray","argument-exception","input-validation"],"backgroundTag":"invalid-argument-format","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"}