c# narrowing conversion won't generate exception-Collection of common programming errors
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.