I cannot understand why the code below compiles.
public void Overflow()
{
Int16 s = 32767;
s = (Int16) (s + 1);
}
At the compile time it is obvious that (s+1) is not a Int16 anymore as we know the value of s.
And CLR allows casting to :
- To its own type
- Or any of the base-types (because it is safe)
As Int32 is not Int16 and Int16 is not base type of Int32.
Question: So why the compiler does not fail for the casting above? Can you please explaint it from the CLR and compiler point of view?
Thanks
The type of the expression
s + 1isInt32– both operands are converted toInt32before the addition is performed. So your code is equivalent to:So the overflow only actually occurs in the explicit cast.
Or, to put it another way: because the language specification says so. You should describe one of:
EDIT: Just to make things really clear (based on your comments), the compiler wouldn’t allow this:
when
sis anInt16whatever the value ofsmight be known to be. There’s noInt16 operator+ (Int16, Int16)operator – as shown in section 7.8.4 of the C# 4 spec, the integer addition operators are: