Tuesday, February 10, 2009

why int(xx) != convert.toint(xx)

Lets take code snippet.
    int no = 55;
            object obj = no;
            Int16 shortInt;
            shortInt = Convert.ToInt16(obj);//Hold good
            shortInt = (Int16)obj;//Error

In the above example, we are trying to assign a integer value to a object.
            object obj = no;
As you expect, a boxing happens at that point.

But to our surprise, when we try to unbox the value, we end up in error where as when we use the convert function, it works without issues. 

The concept behind the working is simple.
1) When you box a value with a specific type, you have to unbox the value with the same type. Else you will end up in cast exception error.
2) The convert function first unboxes it with proper type and then casts it to specific type.

Hope it makes it clear.