Reputation:
Consider this code:
private static void Main(string[] args)
{
short age = 123;
object ageObject = age;
//var intAge = (int)ageObject;//Specified cast is not valid.
int newAge= (short)intAge;
Console.ReadLine();
}
I have to assign a short value to object and again cast to int, but when I try to this: var intAge = (int)ageObject;
I get : Specified cast is not valid. I don't know why?
After search in google i found that should cast to short and assign to int:int newAge= (short)intAge;
Why we should casting to short and assign to int?
Why compiler has this behavior?
Upvotes: 2
Views: 3284
Reputation: 21
I didn't understand why you are trying to convert short to object and then int.
You could do short -> int conversion in following ways:
{
short age = 123;
int intAge1 = (short)age;
int intAge2 = (int)age;
int intAge3 = Int16.Parse(age.ToString());
}
Upvotes: 1
Reputation: 10236
A boxed value can only be unboxed to a variable of the exact same type This restriction helped in speed optimization that made .NET 1.x feasible before generics came into picture.Take a look at this
simple value types implement the IConvertible interface. Which you invoke by using the Convert class
short age= 123;
int ix = Convert.ToInt32(age);
Upvotes: 1
Reputation: 3207
The failure is a runtime error.
The reason for it is the age
value has been boxed into an object; unboxing it to the incorrect type (int
) is a failure - it's a short
.
The cast on the line which you've commented out is an unboxing operation, not just a cast.
Upvotes: 5