[Mono-dev] InvalidCastException - which makes no sense
Miguel de Icaza
miguel at xamarin.com
Fri Oct 24 21:28:25 UTC 2014
Hello,
What happens is this. The value returned from ExecuteScalar is boxed.
This basically means that you have a wrapper that indicates the type of the
boxed object, as well as the contents of the boxed object.
The reality is that: (Int64) (scalar) and (Int32) (Int64) (scalar) perform
different operations on this context.
This is what actually happens on the second case:
tmp = Unbox-the-value-which-i-know-is-a-64-bit-value (scalar)
tmp32 = explicit-cast-64-to-32 tmp
They happen to have the same syntax, but they are different operations.
When you tried doing "(Int32) scalar", you were telling the compiler
"unbox-the-value-which-i-know-is-32-bit-value", but when the runtime went
to unbox this, it noticed it was 64, so it told you "InvalidCastException"
On Fri, Oct 24, 2014 at 5:23 PM, Edward Ned Harvey (mono) <
edward.harvey.mono at clevertrove.com> wrote:
> 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.
>
> _______________________________________________
> Mono-devel-list mailing list
> Mono-devel-list at lists.ximian.com
> http://lists.ximian.com/mailman/listinfo/mono-devel-list
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.ximian.com/pipermail/mono-devel-list/attachments/20141024/71658caa/attachment-0001.html>
More information about the Mono-devel-list
mailing list