As part of doing some writing about C#, I have noticed what appears to be peculiar behavior for the short data type.
The C# specification states:
"If the literal has no suffix, it has the first of these types in which its value can be represented: int, uint, long, ulong."
and that
The implicit numeric conversions are: - From short to int, long, float, double, or decimal. - From int to long, float, double, or decimal.
However, "short number = 1" is allowed without an explicit cast. If 1 is an int as indicated by the spec., then why is no explicit cast required? Interestingly, there is no way (at least from my reading of the C# spec. to express a literal short.). I am not sure why?
Also, numeric operators with short operands appear to return int. The following code doesn't work for short but works perfectly if number is declared as an int.
short number = 1; number = 2 + 2; number += 2; number = number + 2; // Error: Cannot implicitly convert type 'int' to 'short' number = number + (short)2; // Error: Cannot implicitly convert type 'int' to 'short' number = number + number; // Error: Cannot implicitly convert type 'int' to 'short'
By the way, this works in C++ so I presume it was an explicitly decision not to support it.
3:10:11 AM
|