Comparing a "short" to a "ulong" causes compiler error CS0034 #2015
-
In my codebase I have the following code: ulong ulongValue = 0;
if (ulongValue > long.MaxValue) { /*...*/ }
else if (ulongValue > uint.MaxValue) { /*...*/ }
else if (ulongValue > int.MaxValue) { /*...*/ }
else if (ulongValue > ushort.MaxValue) { /*...*/ }
else if (ulongValue > short.MaxValue) { /*...*/ }
else if (ulongValue > byte.MaxValue) { /*...*/ } The statement
All other comparisons work just fine. I could of course cast I already had a look at the latest source files for the referenced types and found that the implementation of the
Is this intended bavior and I am doing something wrong here? NB: The full .NET framework shows the same behavior. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
Issue for C# compiler https://github.com/dotnet/roslyn rather than runtime? |
Beta Was this translation helpful? Give feedback.
-
This is intended behavior. (Section numbers below refer to C# Language Specification 5.0.) The reason the
Emphasis mine. Not all values of The reason the
There is no rule like this for 16 or 8 bit types. Additionally, if you modify your code to not use a constant, you can see it no longer compiles: void Test(ulong ulongValue)
{
int maxInt = int.MaxValue;
if (ulongValue > maxInt) {} // CS0034
} |
Beta Was this translation helpful? Give feedback.
-
Thank you for clarifying this! |
Beta Was this translation helpful? Give feedback.
This is intended behavior. (Section numbers below refer to C# Language Specification 5.0.)
The reason the
ulong
/short
comparison is invalid is due to this rule: (§4.1.5 / Integral Types)Emphasis mine. Not all values of
short
can be converted to all values ofulong
, so the conversion isn't permitted.The reason the
ulong
/int.MaxValue
andulong
/long.MaxValue
comparisons are allowed is due to this one: (§6.1.9 / Implicit constant expression conversions)