[Mono-dev] InvalidCastException - which makes no sense

Edward Ned Harvey (mono) edward.harvey.mono at clevertrove.com
Fri Oct 24 21:23:46 UTC 2014

This is a fun one.  I'd love it if anyone could explain this to me.

using (var command = new SqliteCommand(@"SELECT COUNT(*) FROM someTable WHERE someColumn = @someValue ", dbConn))
    command.Parameters.Add(new SqliteParameter("someValue", "foobar"));
    object scalar = command.ExecuteScalar();        // object returned has type Int64
    Int64 count64 = (Int64)(scalar);                              // works fine.  Value is 0
    Int32 count32 = (Int32)(Int64)(scalar);                // works fine.  Value is 0
    Int32 count = (Int32)(scalar);                   // throws InvalidCastException

In the above, scalar is obviously an object, but the object returned by ExecuteScalar() is of type Int64.  The value is 0.

This works fine:
Int64 count64 = (Int64)(scalar);

This works fine:
Int32 count32 = (Int32)(Int64)(scalar);

This throws InvalidCastException:
Int32 count = (Int32)(scalar);

The best I can gather, the object needs to be cast to Int64 before it can be cast to Int32.  Which makes no sense to me, but that's the way it is.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.ximian.com/pipermail/mono-devel-list/attachments/20141024/0edbab28/attachment.html>

More information about the Mono-devel-list mailing list