I had following piece of code
try
{
object s = new object();
s = 10;
Console.WriteLine(\"{0}\", Convert.ToInt16(s));
Console.WriteLine(\"{0}\", (In
In the problem line you are attempting to cast something that is not Int16 (probably Int32?) into the Int16 type. If you change the assignment to this I bet it will work (ideone):
object s, s2;
s = Convert.ToInt16(10);
s2 = 10;
Console.WriteLine("Types: {0} and {1}", s.GetType(), s2.GetType());
Console.WriteLine("s as Int16 (works): {0}", (Int16)s);
Console.WriteLine("s2 as Int16 (error): {0}", (Int16)s2);
Output:
Runtime error time: 0.03 memory: 36592 signal:-1
Types: System.Int16 and System.Int32
s as Int16 (works): 10
From the comments, casting Int32 to Int16 directly works becasue the compiler knows they can be converted and does that automatically. When you are working with a bare object though it is going blind and will not automatically convert. This will work for instance:
Console.WriteLine("s2 as Int16 (works): {0}", (Int16)((Int32)s2));