I vaguely understand this, but I would like a concrete explanation as to what's happening. If I construct a HashSet<bool>
with data originally from a byte
array, why exactly does it keep duplicate values? I've tried to debug this but once I have a bool
array, all the elements appear like standard bool
s.
.Net Fiddle: https://dotnetfiddle.net/QOll01
byte[] bytes = new byte[] { 0, 1, 2 };
ReadOnlySpan<byte> span = new(bytes);
ReadOnlySpan<bool> boolSpan = MemoryMarshal.Cast<byte, bool>(span);
bool[] bools = boolSpan.ToArray();
Console.WriteLine(string.Join(", ", bools)); // False, True, True
Console.WriteLine(new HashSet<bool>(bools).Count); // 3??
Console.WriteLine(string.Join(", ", new HashSet<bool>(bools))); // False, True, True
My guess would be that the memory for a bool
can actually be populated with any data. If you set it explicitly then it is probably populated with all 0s or all 1s but it can actually be populated with anything and any value that is not zero is interpreted as true
. Because you are creating your values from numbers, the two true
values actually do contain different numbers in memory so, while they are the same when interpreted as bool
values, they are actually being compared as numbers under the hood and are thus not equal.
To test, I changed this:
byte[] bytes = new byte[] { 0, 1, 2 };
to this:
byte[] bytes = new byte[] { 0, 1, 2, 1, 2 };
and the output was this:
False, True, True, True, True 3 False, True, True
That appears to support the theory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With