I found some weird behaviour when working with numbers in C# (.NET8 version 8.0.400
).
I created a custom type to wrap numbers, this is the minimalized code to showcase the behavior:
struct Mystery<T>(T value)
where T : IBinaryInteger<T>
{
public T Value { get; } = value;
public int GetByteCount() => Value.GetByteCount();
}
Execution code:
Mystery<BigInteger> mystery = new(short.MaxValue);
// Mystery<BigInteger> mystery = new(new BigInteger(short.MaxValue)); // same behavior
Console.WriteLine(mystery.GetByteCount()); // 4
Console.WriteLine(mystery.Value.GetByteCount()); // 2
Console.WriteLine(((IBinaryInteger<BigInteger>)mystery.Value).GetByteCount()); // 4
Output:
4
2
4
Since I created the Mystery
type to wrap around the number, I would want mystery.GetByteCount()
to behave exactly like Value.GetByteCount()
.
However, as seen in the output, my code is not working as intended.
Where did I go wrong?