Sharing the Joy of Software/Delphi in the .NET world

Friday, July 30, 2004

Strange Addition: Trying to add 1 to a type short in C#

OK, I have to admit I am still getting ramped up on C# and .NET but I have found something that is very strange and want to see if anyone can explain. I have a line of code "short colID = colIndex + 1;" that gives an error "Cannot implicitly convert type 'int' to 'short'" at build time. I would assume that the compiler could convert "1" to a short and add it to the short variable colIndex. So here is the line of code that works "short colID = (short)(colIndex + 1);" I assume that someone can share the wisdom as to why it is a bit more complicated to add 1 to a short. I come from the Delphi side of the programming world. Does the CLR need this syntax?

1 Comments:

  • I just tried

    short colIndex = 5;
    Console.WriteLine((colIndex + colIndex).GetType());

    and got "System.Int32". So it looks like, in C# at least, applying the + operator to two Int16s will always return an Int32.

    This is not entirely surprising, since Int16 + Int16 could overflow an Int16. (What is surprising that Byte + Byte also returns an Int32! By that same logic, I might expect it to return an Int16.)

    This was probably a design decision by the C# team. Int16 is mostly there for backwards compatibility. It's not a data type you actually need in a 32-bit world, except for interop and data file formats. When you want an int, you're expected to use an int (or a long, if you need 64 bits). So when there's any question of what data type an operation should return, they return an int or a long.

    There are two obvious fixes:
    1. Cast the result to a short (after adding), as you have done.
    2. Don't use short.

    Is there a reason why you're using short? You're not saving enough space to notice, and you're possibly slowing your code down by using a type that may not be dword-aligned.

    By Anonymous Anonymous, at 11:39 AM  

Post a Comment

<< Home