invalid cast

This piece of code works fine and needs no explicit cast in vb.net.

itemId = arrCart(cartId, i)

When I converted it to C#, however, it complained that it cannot do the implicit conversion. So I tried:

itemId = (int)arrCart[cartId, i];

But I get an exception error read: Specified cast is not valid.
itemId is an integer and arrCart is a two dimensional array object:
int itemtId;
object[,] arrCart;
Can anyone tell me how to correct this 


Answer this question

invalid cast

  • Ian Roof - MSFT

    Good point. I'll have to go over my code and see if this is feasible. Thanks!
  • Michael Rajan

    Try Convert.ToInt16 instead of the cast. At a guess, it could be a SQL numeric type



  • ocertain

    Bingo! That worked. Thank you!
  • le_sloth

    Why have you made an array of objects instead of ints You're boxing and unboxing all the time as a result, which will hurt performance, as well as leaving you open to these sort of problems.



  • Piocon

    What is in the array when you get the exception It could be anything (it could be a customer object) that can't possibly be converted to an integer.

    if you add a line right before

    itemId = (int)arrCart[cartId, i];

    Trace.WriteLine(arrCart[cartId, i].ToString()); what do you get


  • Xavier Espinoza

    When I do Trace.Write, it gives me a numeric value of 20.
  • invalid cast