TheAlgorithms/C-Sharp · error · ArgumentException
The sequence may only contain ones or zeros
Error message
The sequence may only contain ones or zeros
What it means
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.
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.
Example fix
// before
var ba = new BitArray("10 01"); // space -> throws
// after
var raw = "10 01";
var seq = raw.Replace(" ", "");
if (!System.Text.RegularExpressions.Regex.IsMatch(seq, "^[01]+$"))
throw new ArgumentException("Invalid binary sequence");
var ba = new BitArray(seq); Defensive patterns
Strategy: validation
Validate before calling
bool IsValidSequence(string s) => System.Text.RegularExpressions.Regex.IsMatch(s?.Trim() ?? "", "^[01]+$");
Type guard
bool IsBinaryString(string s) => !string.IsNullOrEmpty(s) && s.All(c => c is '0' or '1');
Try / catch
try { var ba = new BitArray(seq); } catch (ArgumentException ex) when (ex.Message.Contains("ones or zeros")) { /* sanitize and retry or reject input */ } Prevention
- 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.
When it happens
Trigger: 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.).
Common situations: 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.
Understand the failure class
Background: "Invalid ... format", "must be in format X", "does not look like a ..." — invalid argument format errors across CLI tools and libraries — this error's family across 17 libraries.
Related errors
- Value is too big to fit into Int64
- Value is too big to fit into Int32
- Capacity must be at least 1.
- The length of key should be divisible by 16
- Discount rate cannot be negative
AI-assisted analysis of TheAlgorithms/C-Sharp@96e2905cab (2026-09-13).
Data as JSON: /api/errors/2958d1e82d100697.
Report an issue: GitHub.
Appendix: source
Thrown at DataStructures/BitArray.cs:769
return false;
}
}
return true;
}
/// <summary>
/// Gets has-code of bit-array.
/// Assumes bit-array length must been smaller or equal to 32.
/// </summary>
/// <returns>hash-code for this BitArray instance.</returns>
public override int GetHashCode() => ToInt32();
private static void ThrowIfSequenceIsInvalid(string sequence)
{
if (!Match(sequence))
{
throw new ArgumentException("The sequence may only contain ones or zeros");
}
}
/// <summary>
/// Utility method for checking a given sequence contains only zeros and ones.
/// This method will used in Constructor (sequence : string) and Compile(sequence : string).
/// </summary>
/// <param name="sequence">String sequence.</param>
/// <returns>returns True if sequence contains only zeros and ones; False otherwise.</returns>
private static bool Match(string sequence) => sequence.All(ch => ch == '0' || ch == '1');
}
View on GitHub (pinned to 96e2905cab)