From the C# Type Conversion Tables(http://msdn.microsoft.com/en-us/library/08h86h00.aspx): “A narrowing conversion can also result in a loss of information for other data types. However, an OverflowException is thrown if the value of a type that is being converted falls outside of the range specified by the target type’s MaxValue and MinValue fields, and the conversion is checked by the runtime to ensure that the value of the target type does not exceed its MaxValue or MinValue.”
So I was expecting the following code to generate an exception:
static void Main() {
int numb1 = 333333333;
short numb2 = (short)numb1;
Console.WriteLine("Value of numb1 is {0}", numb1);
Console.WriteLine("Type of numb1 is {0}", numb1.GetType());
Console.WriteLine("MinValue of int is {0}", int.MinValue);
Console.WriteLine("MaxValue of int is {0}\n", int.MaxValue);
Console.WriteLine("Value of numb2 is {0}", numb2);
Console.WriteLine("Type of numb2 is {0}", numb2.GetType());
Console.WriteLine("MinValue of short is {0}", short.MinValue);
Console.WriteLine("MaxValue of short is {0}", short.MaxValue);
Console.ReadKey();
}
but instead numb2 gets a value of 17237. I don’t know where this value comes from and I really don’t understand why an overflow exception wasn’t generated.
Any suggestion is highly appreciated! Thanks.
Numeric conversions are not checked by default. You can force this by using a
checkedblock:Alternatively you can use the
Convertclass which does check conversions:There’s also a checked compiler option
The value 17237 is simply the lower 16 bits of 333333333 (i.e. 333333333 truncated to fit in a short):