The reason this is the case is because the CLR evaluation stack uses 4-byte
and 8-byte integers, so the short will get widened when it is pushed on the
stack, and then the add instruction comes up with an Int32 result.
The compiler could generate code to automatically cast this back to short
for you, however this would be hiding some of the details of what was
actually going on, would be limiting functionality, and would be prone to
errors. Consider the following method:
public void Method()
{
checked {
short a = 0x7fff;
short b = 0x7fff;
int c = a + b;
}
}
The method will work with the current system. Suppose, however, that the
compiler forced a cast back to short behind the scenes. Then the last line
would change to something like:
int c = (int)(short)(a + b); // where the cast to short is added by
the hypothetical compiler
Not only would you get an invalid result due to overflow errors on the cast
to short, but in this case it would always throw an exception because it is
in a checked context.
-Mark
--
Mark Andersen, Visual C# Team
This posting is provided "AS IS" with no warranties, and confers no rights.
Use of included script samples are subject to the terms specified at
http://www.microsoft.com/info/cpyright.htm
--------------------
From: "NilsNilsson" <aninilsnilsson@hotmail.com>
References: <u0d5zGngDHA.1684@TK2MSFTNGP10.phx.gbl>
Subject: Re: Problems with short and + operator
Date: Wed, 24 Sep 2003 10:17:56 +0200
Lines: 32
X-Priority: 3
X-MSMail-Priority: Normal
X-Newsreader: Microsoft Outlook Express 6.00.2800.1158
X-MimeOLE: Produced By Microsoft MimeOLE V6.00.2800.1165
Message-ID: <u9G9bQngDHA.696@TK2MSFTNGP09.phx.gbl>
Newsgroups: microsoft.public.dotnet.languages.csharp
NNTP-Posting-Host: server2.triona.se 217.31.172.231
Path: cpmsftngxa06.phx.gbl!TK2MSFTNGP08.phx.gbl!TK2MSFTNGP09.phx.gbl
Xref: cpmsftngxa06.phx.gbl microsoft.public.dotnet.languages.csharp:186980
X-Tomcat-NG: microsoft.public.dotnet.languages.csharp
Thanks,
it works!
But I still think this is strange feature i C#?
/Anders
'int'