Repository navigation
Description
Proposal
Add a section to docs/design/specs/Ecma-335-Augments.md stating that a CLI bool is either 0 (false) or 1 (true). Any other bit pattern is an invalid Boolean value. Consuming one gives unspecified results, but memory safety must still hold.
This matches what Roslyn, the BCL, the VM and the documentation already assume today. The only place that still holds the ECMA "any non-zero is true" rule is the JIT, and it pays for that with missed optimizations.
What ECMA-335 says today
§III.1.1.2 Boolean data type (PDF p.319):
A CLI Boolean type occupies 1 byte in memory. A bit pattern of all zeroes denotes a value of false. A bit pattern with any one or more bits set (analogous to a non-zero integer) denotes a value of true.
Partition IV, System.Boolean:
the representation of false is all-bits-zero, and the representation of true is unspecified except that it shall have at least one bit set.
The spec contradicts this rule in several places:
- §II.23.3 (custom attribute blobs): "A bool is a single byte with value 0 (false) or 1 (true)".
- §I.8.2.5.1 (identity): two value-type values are identical "if and only if the bit sequences of the values are the same". So a true stored as
1and a true stored as2are both true but not identical. ceq/cgt/cltalways push exactly0or1.
Reality: everything above the JIT already assumes 0/1
Roslyn
Documented in Boolean Representation.md:
The C# and VB compilers represent
trueandfalsewith the single byte values1and0, respectively, and assume that any boolean values that they are working with are restricted to being represented by these two underlying values. [...] it is the programmer's responsibility to normalize such incoming values.
Codegen follows from that:
| C# | IL |
|---|---|
x == y |
ceq |
x & y |
and |
x && y (simple right operand, also in Debug and in branch position) |
and |
x == true |
x |
switch (b) { case true: } |
ldc.i4.1; beq |
BCL
Boolean.Equalsism_value == obj, a raw byte compare.Boolean.CompareTois not antisymmetric for non-0/1 values.GetHashCodenormalizes.RuntimeHelpers.IsBitwiseEquatable<bool>()istrueon CoreCLR (jitinterface.cpp), NativeAOT/crossgen2 (RuntimeHelpersIntrinsics.cs) and Mono. As a result every vectorizedIndexOf/Contains/SequenceEqual/Countcompares bytes.ValueType.Equals/GetHashCodeuse the memcmp fast path for structs withboolfields. Only R4/R8 fields are excluded (comutilnative.cpp, NativeAOTComparerIntrinsics.cs).Interlocked.CompareExchange<bool>andInterlocked.And<bool>do byte arithmetic.
Docs
- Unsafe code best practices say "anything other than 0 or 1 likely leads to unreliable behavior".
- The
System.BooleanAPI docs say "A value of 1 represents true; a value of 0 represents false".
Non-normalized bools are already broken today
A bool holding byte 2 prints True and takes the if (b) branch, but it is not equal to true. In practice the runtime has 255 distinct values of true.
static bool Mk(byte v) => Unsafe.BitCast<byte, bool>(v);
static void Main() {
bool one = Mk(1), two = Mk(2); // both "true" per ECMA
Console.WriteLine(one == two); // False
Console.WriteLine(one.Equals(two)); // False
Console.WriteLine(EqualityComparer<bool>.Default.Equals(one, two)); // False
Console.WriteLine(one && two); // False (Roslyn emits `and`)
Console.WriteLine(one & two); // False
Console.WriteLine($"{two.CompareTo(true)} {true.CompareTo(two)}"); // 1 1
Console.WriteLine(Array.IndexOf(new[] { false, two }, true)); // -1
Console.WriteLine(new[] { false, two }.AsSpan().IndexOf(true)); // -1
Console.WriteLine(new HashSet<bool> { one }.Contains(two)); // False
Console.WriteLine(new HashSet<bool> { true, two, false }.Count); // 3
Console.WriteLine(new SortedSet<bool> { true, two, false }.Count); // 3
Console.WriteLine(new S { B = one }.Equals(new S { B = two })); // False (memcmp fast path)
bool loc = two;
Interlocked.And(ref loc, true);
Console.WriteLine(loc); // False
}
struct S { public bool B; }More observed results with the same setup:
Array.Sort(new bool[] { 2, 1, 0, 2, 1, 0, 1, 2 })(written as raw bytes) produces[0, 0, 2, 1, 2, 1, 1, 2], which is not sorted.span.Count(true) + span.Count(false) != span.Length.Dictionary<bool, T>can hold bothtrueand2as separate keys.
Every output above was identical across these configurations:
- FullOpts (
TieredCompilation=0) and MinOpts - R2R on and off
- the CoreCLR interpreter
- x64 and arm64 codegen
So these results don't depend on tiering or on any JIT optimization. They follow directly from the IL Roslyn emits and from how the BCL and VM implement equality.
Supported ways to get a non-0/1 bool (no Unsafe at the use site)
[assembly: DisableRuntimeMarshalling]: P/Invokes,delegate* unmanaged,[UnmanagedCallersOnly]and blittable structs withboolfields pass the native byte through as-is. This is documented (Compatibility.md), and the testPInvokeAssemblyMarshallingDisabled/PInvokes.csNoBooleanNormalizationasserts it. Native code returning a WindowsBOOLEANorflags & 4asuint8_tis common.- Raw byte copies:
Buffer.BlockCopyfrombyte[]tobool[],MemoryMarshal.Cast/Read<bool>,MemoryMappedViewAccessor.Read<bool>, andArrayPool<bool>arrays reused after byte-level writes. - Reflection: custom attribute instances get the raw blob byte, while
CustomAttributeDatanormalizes the same byte. The two APIs disagree for blob value2. - IL: any
stind.i1/stfld boolof an int is a truncating store. The spec's own example in §II.14.5 storesnot(false)(0xFF) into aboolfield.
When runtime marshalling is enabled, the built-in marshallers (VM, NativeAOT, LibraryImport generator) all normalize to 0/1.
Cost of the current wording
The JIT is the only component that follows ECMA here, and that has cost both correctness bugs and performance.
- JIT: Remove TYP_BOOL #90981 "JIT: Remove TYP_BOOL" fixed a Fuzzlyn bug (JIT: Assertion failed '!"Bad CastToType() in gtFoldExprConst() for a cast from long" #90798) with this rationale: "We try to use it in some cases to make assumptions about the value being 0/1, but this logic is not correct in the face of unnormalized booleans." JIT: Remove GTF_BOOLEAN #104779 removed
GTF_BOOLEAN. JIT: Fix SELECT to relop changing type and check cond evaluates to 0 or 1 #127933 added guards because aboolcondition "could be anything". - Blocked optimizations:
- Merge nested branches into AND test #101820: merge
if (a) if (b)into a singlea & btest. Roslyn already does this for&&. - Inefficient Boolean comparisons on Arm64 #75852: arm64 bool compares.
optimizebools.cpp: "Anding requires both values to be 0 or 1".- JIT: implied Boolean range assertions for local prop #109481: [0..1] range assertions for bool locals.
- Merge nested branches into AND test #101820: merge
- Defensive normalization in libraries:
BitArray: "would not work for some CLR bools".TensorPrimitives:& Vector<byte>.Oneon every store.- Nrbf decoder: "optimizing compiler or JIT could elide this".
BitConverter.ToBoolean,BinaryReader.ReadBoolean,UnmanagedMemoryAccessor.ReadBoolean.
Prior discussion
- C# Compiler is not consistent with the CLR for the underlying representation of bool roslyn#24652, Optimizing a conditional AND to a logical AND requires coercion roslyn#14262, Conditional logical operator && not functioning as described in spec when working with 'corrupted' bool values roslyn#12211, Unexpected IL on switch statement with bool roslyn#21200: Roslyn's position is "0/1 by design". One comment in complete payment #14262: "If there are any docs saying that bool values other than 1 and 0 are ok for universal interop purposes, they are misleading and need changing."
- Clarify the representation of Boolean value true csharpstandard#898: the C# standard now says the representation of
trueis unspecified. A reviewer suggested "define false as 0x0, true as 0x1, and state it is undefined behavior if any value in the range 0x2 - 0xFF is used". - Enumerating type safety guarantees in MemoryMarshal and friends #41418: "A bool with a value 2 .. 255 will never naturally occur in the runtime".
- Problem when comparing boolean values after IL conv.i1 #12872 ("The behavior of these is basically undefined"), [API Proposal]:
Interlocked.[Compare]Exchangeforbool#100914 (Interlockedon bool) and Improve performance of Convert.ToInt32(bool) and related functions coreclr#16138: "the JIT and the C# compiler tend to assume that bool is either 0 or 1 [...] The ship has sailed a long time ago."
Proposed augment text
Boolean representation
Section "III.1.1.2 Boolean data type" is replaced with: A CLI Boolean type occupies 1 byte in memory. The bit pattern 0x00 denotes false and the bit pattern 0x01 denotes true. All other bit patterns are invalid Boolean values. The result of any operation that consumes an invalid Boolean value (including branches, comparisons, conversions and calls) is unspecified, but it shall not compromise memory safety or type safety. For the purpose of stack operations boolean values are treated as unsigned 1-byte integers (§III.1.1.1).
In Partition IV, the representation of
trueforSystem.Booleanis changed to the value 1.The example in section "II.14.5 Method pointers" is changed to use
ldc.i4.1; xorinstead ofnotto toggle the Boolean field.Native data type
boolin II.7.4 (4-byte Win32 BOOL) is unaffected. Marshalling from native Boolean representations to a CLIboolis expected to normalize to 0/1 when runtime marshalling is enabled.
Open questions
- Should
DisableRuntimeMarshalling(and[UnmanagedCallersOnly]/delegate* unmanaged<bool>) start normalizing, or stay documented as "the caller must pass 0/1"? - Metadata readers: keep accepting
0xFFin constant and attribute blobs, since some writers emit it (BlobReader.cs)?
Activity
EgorBo commentedon Nov 24, 2026
cc @jkotas @dotnet/jit-contrib
dotnet-policy-service commentedon Nov 24, 2026
Tagging subscribers to this area: @JulieLeeMSFT, @jakobbotsch
See info in area-owners.md if you want to be subscribed.
jkotas commentedon Nov 24, 2026
Managed C++ says hello...
EgorBo commentedon Nov 24, 2026
I guess my point is - we either fix all the places (APIs, VM) where we assume it's 0/1 only or change the spec, it seems like Managed C++ technically faces with bugs then.
jkotas commentedon Nov 24, 2026
Not necessarily. For interop with C#, managed C++ just needs to ensure that they do not return or store de-normalized bool values where C# can see them. The codegen can use de-normalized bool values internally any way it wants without impacting C# interop.
EgorBo commentedon Nov 24, 2026
@jkotas btw, lack of managed C++ on non-Windows allows us to make the 0/1 assumption in jit?
hamarb123 commentedon Nov 24, 2026
Could we also add a new compilation relaxation bit, or similar attribute/flag (this one would be free ito dll size tho iirc), and get roslyn to emit it for C# (either based on the bit definiton or some runtime feature field presence), which would allow all C# code to benefit (the majority case), while allowing us to keep the behaviour in IL and C++/CLI and other langs that might rely on it as-is (unless they choose to opt-in via this mechanism)?
Edit: this would be similar to exception wrapping; and would also be similar to us interpreting lack of
[UnscopedRef]as non-escaping based on the c# ref safety rules version on the dll; and is also similar to the disable marshalling attribute too (but ofc this is not automatically emitted by roslyn); so the idea has some precendent.tannergooding commentedon Nov 24, 2026
You can still have other languages that expect or deal with bools that are values other than 0/1.
As it is today, other languages and interop in general is free to handle and normalize their "non-standard" bools as they see fit. If you start enforcing that it can only be 0/1 then they have no recourse to fix things themselves.
I'm extremely skeptical that this would provide meaningful benefit, particularly compared to other considerations like IPA and simply tracking that a bool was never produced by something that could've been different.
Devs who already know or expect it to be normalized can even get it converted for zero-cost using
Unsafe.BitCastalready (it just emits themovzx eax, althat abytewould do), so if it is truly some perf critical edge case you have options.am11 commentedon Nov 25, 2026
@EgorBo, for if-conversion, #135757 normalizes it in value numbing to exactly 0 or 1 then rest of the phases can fold stuff with confidence.