2

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?

Erik Schierboom
  • 16,301
  • 10
  • 64
  • 81
  • It works perfect on my end... – It'sNotALie. Jul 19 '13 at 11:00
  • When unboxing a struct you have to cast to the exact type, `short` in this case. From there you can convert to an `int`. – Lee Jul 19 '13 at 11:02
  • `(int)(short)ageObject;` works – Tim Schmelter Jul 19 '13 at 11:03
  • possible duplicate of [Why does (int)(object)10m throw "Specified cast is not valid" exception?](http://stackoverflow.com/questions/3953391/why-does-intobject10m-throw-specified-cast-is-not-valid-exception) – Soner Gönül Jul 19 '13 at 11:13
  • This link will explain you why [Representation and identity](http://ericlippert.com/2009/03/03/representation-and-identity/) – Sriram Sakthivel Jul 19 '13 at 11:04
  • I can't comment I'm still new to the community, your answer is here:
    [http://stackoverflow.com/questions/3953391/why-does-intobject10m-throw-specified-cast-is-not-valid-exception](http://stackoverflow.com/questions/3953391/why-does-intobject10m-throw-specified-cast-is-not-valid-exception)
    – sarepta Jul 19 '13 at 11:11

4 Answers4

5

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.

SteveLove
  • 3,137
  • 15
  • 17
2

Use

Convert.ToInt32(ageObject) instead.

It will work

Murugavel
  • 269
  • 1
  • 2
  • 9
1

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());
}
uguracar
  • 21
  • 5
0

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);
Community
  • 1
  • 1
Rohit
  • 10,056
  • 7
  • 50
  • 82