Mark Michaelis' Weblog :
Updated: 9/1/2004; 7:03:36 AM.

 








Subscribe to "Mark Michaelis' Weblog" in Radio UserLand.

Click to see the XML version of this web page.

Click here to send an email to the editor of this weblog.

Subscribe To
Mark's Weblog

 
 

Sunday, August 10, 2003

What's with the C# shorts?
Google Search It

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   []    comment []

© Copyright 2004 Mark Michaelis.



 


August 2003
Sun Mon Tue Wed Thu Fri Sat
          1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31            
Jul   Sep


Recent Posts