The usual C# equivalent to "reinterpret cast" is to define a struct
with fields of the types you want to reinterpret. That approach works fine in most cases. In your case, that would look like this:
[StructLayout(LayoutKind.Explicit)]
struct BoolByte
{
[FieldOffset(0)]
public bool Bool;
[FieldOffset(0)]
public byte Byte;
}
Then you can do something like this:
BoolByte bb = new BoolByte();
bb.Bool = true;
int myInt = bb.Byte;
Note that you only have to initialize the variable once, then you can set Bool
and retrieve Byte
as often as you like. This should perform as well or better than any approach involving unsafe code, calling methods, etc., especially with respect to addressing any branch-prediction issues.
It's important to point out that if you can read a bool
as a byte
, then of course anyone can write a bool
as a byte
, and the actual int
value of the bool
when it's true
may or may not be 1
. It technically could be any non-zero value.
All that said, this will make the code a lot harder to maintain. Both because of the lack of guarantees of what a true
value actually looks like, and just because of the added complexity. It would be extremely rare to run into a real-world scenario that suffers from the missed branch-prediction issue you're asking about. Even if you had a legitimate real-world example, it's arguable that it would be better solved some other way. The exact alternative would depend on the specific real-world example, but one example might be to keep the data organized in a way that allows for batch processing on a given condition instead of testing for each element.
I strongly advise against doing something like this, until you have a demonstrated, reproducible real-world problem, and have exhausted other more idiomatic and maintainable options.
Dictionary<bool, byte>
feels like overkill. Hash-based lookup seems on the heavy side for what we are trying to do. – Contrapuntalbool
. You can't rely on1
for atrue
value. – Granititetrue
values other than that they are non-zero. As for measurements: The linked question and its accepted answer cover that well, in my opinion. Otherwise, you may consider this a theoretical exercise, to be measured whenever it is applied in a particular scenario. Let's say that I want to have a solution available when the branch prediction failure is determined to be an issue. And yes, that requires something inline that is very efficient! – Contrapuntalbool
test, in my answer below. – GranititeSystem.Convert.ToByte(bool)
branch? – Monochrome