Re: Problems with (Cast)

Tech-Archive recommends: Fix windows errors by optimizing your registry



Daniel Groh wrote:
> I'm facing this error:
> Error Message:Specified cast is not valid.
>
> this line:
> char chrTipoPessoa = (char)sqlCmd.ExecuteScalar();
>
> It should returns the letter "F" or "J"!
> but with (string) it works normal...I already checked and there's no
space!
>
> Why I'm getting this error when I try to cast as char ?

If it's this method:

[C#]
public virtual object ExecuteScalar();

then you're not being returned an object that casts to a char
value. I wouldn't expect a single-character string to cast to
a char, although I didn't check.

Try something like this, and then use the debugger to check the
type of obj if it still doesn't work:

object obj = sqlCmd.ExecuteScalar();
if (obj is char) {
return (char) obj;
}
if (obj is string) {
string s = obj as string;
return s.Length == 1 ? s[0] : 0; // yeuch, but you get the idea
}
throw new Exception( "Unexpected return from SQL command: " +
obj.ToString() );

etc etc

I hope this helps

Dave D

.



Relevant Pages

  • Re: Confused about using Reflection to examine a collection
    ... the precise type that Reflection is saying it is. ... say that 'obj' is actually a custom collection. ... If it were a basic type, such as 'string' then I would do a cast like this: ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: tree example
    ... understand the tree example but no what I just memtioned. ... The only occurrence of the string "(char *)" in page 143 is a cast ... acknowledge that malloc and it siblings do not need this type of cast. ...
    (comp.lang.c)
  • Re: Problems with (Cast)
    ... >> Why I'm getting this error when I try to cast as char? ... I wouldn't expect a single-character string to cast to ... > type of obj if it still doesn't work: ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Comment on trim string function please
    ... I've not been following why the cast is important; ... Serious bug. ... unsigned char. ... I appear to "getting" a signed 8-bit integer value from my string, ...
    (comp.lang.c)
  • Is a void * equivalent to a char *?
    ... Is the printfstatement correct? ... Or is a cast to char * required for vp? ... That is, assuming a void * is pointing to a string, what is the proper way ...
    (comp.lang.c)