Re: Why "Specified cast is not valid" error?

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance

From: Jon Skeet [C# MVP] (skeet_at_pobox.com)
Date: 11/23/04


Date: Tue, 23 Nov 2004 08:40:21 -0000

Jack MacRank <jack@macrank.com> wrote:
> I set a breakpoint and looked at the GetType() of "retval" after the query
> executed. I was surprised to see it was of Int64 type. I didn't know
> C#/.NET automatically converted an object variable to another type...I
> thought it would just be a generic object type and then I could cast it to
> whatever I wanted it to.
>
> I'm still a little confused why I can't cast an Int64 to String but I will
> take your advice and use .ToString() and Convert.ToInt32() when I want a
> string or integer.
>
> Thanks to everyone who responded to my question!

I *strongly* suggest you abandon database access for the moment and
read a good book on the basics of .NET, in particular the type system.
Then read up on what casts do in C#.

I know it may sound like a backward step, but getting a good handle on
the basics is vital for writing decent code. For instance, you don't
always want to call .ToString or Convert.ToInt32() - it depends
entirely on the circumstances.

-- 
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too


Relevant Pages

  • Re: Why "Specified cast is not valid" error?
    ... I was surprised to see it was of Int64 type. ... thought it would just be a generic object type and then I could cast it to ... I'm still a little confused why I can't cast an Int64 to String but I will ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: invalid class typecast
    ... > Using TLargeIntField field type as follows, ... typecast exception. ... Why do you cast it as TLargeInt? ... This means the INT64 type while MS Access ...
    (borland.public.delphi.database.ado)
  • Re: int32 Vs Int
    ... FYI there is also an int64 type ... couldn't find a reference to this type. ... the same as string Vs String and that int is simply a shortened form of ... int32 - both of them representing 32 bit signed integers? ...
    (microsoft.public.dotnet.languages.csharp)