Implicit Casting Issues (Integer literals)


I'm developing custom Int/UInt classes for larger integers. They work great with assignment/casting/arithmetic, etc. However, it exposed an issue that occurs with xunit and MSTest.

Here's my code:

UInt240 x = 0x7fffffff;
Assert.Equal(0x7fffffff, x);

The issue is that if I supply an unsigned type on the right side, and provide a literal on the left side, it will interpret the literal as an "int" (or relevant signed type that can hold the value), and not be able to cast to the unsigned type (because C# doesn't implicitly cast signed to unsigned types, and xunit is trying to implicitly cast to a common type). MSTest will allow it, interpreting both as "object" objects, but will error because although values match, the types differ.

The same happens with primitives as well normally:

ulong x = 0x7fffffff;
Assert.Equal(0x7fffffff, x);

Is there anything I can do to avoid implicitly casting (ie: "Assert.Equal((ulong)0x7fffffff, x);" )? It would make the code horribly bloated to have to cast types all over the place.

asked on Stack Overflow Sep 19, 2018 by DS7 • edited Sep 19, 2018 by DS7

1 Answer


When you declare a literal, you can declare the type, using a suffix. That lets you specify the type of the literal without a cast.

So maybe try this:

UInt240 x = 0x7fffffffUL;
Assert.Equal(0x7fffffffUL, x);
answered on Stack Overflow Sep 19, 2018 by John Wu

User contributions licensed under CC BY-SA 3.0