(int) or convert.ToInt32 ?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hey
I have following "problem".
int id = (int)SQlHelper.ExecuteScala(...) - it returns object ( which is int )
I get invalid cast.

Convert.ToInt32(...) works ok. Why ?
Jarod
 
Hi,

because there si not implicit cast (int) on objects (actually it does not
know how to convert it if you don't tell how, that's why Convert.ToInt32
works. In this function there is a explicit conversion rule. Also there is
another way....

Beacause some return type implements IConvertible (intellisence doesnot
present it so you can check the msdn documentation) you can do this:

int MyValue = ((IConvertible)SQlHelper.ExecuteScalar(....)).ToInt32(null);

actually is faster than Convert as stateted on "Maximizing .NET Performance
Addison-Wells 2002)

Cheers
Salva

--
Salvador Alvarez Patuel
Exony Ltd - London, UK


:
 
int id = (int)SQlHelper.ExecuteScala(...) - it returns object ( which is int )
I get invalid cast.

Convert.ToInt32(...) works ok. Why ?

Casting only works if the type is exactly int (which it probably isn't
in this case). Convert works for other types of boxed integers as well
(byte, short, ushort etc).



Mattias
 
Hi Jarod,
the equivalent of the null value in the db world for NET is System.DBNull
now from your scalar execution if the return is System.DBNull then the cast
will fail since System.DBNull is not a number(byFar...) but the
Convert.ToInt32 function if the value passed throws an exception in our case
it does, it return the integer 0, thus it didn't convert your value
actually.
Hope that helps.
 
hi

you can IF the object is a boxed int , or a type that can be implicitely
converted to int.

My advise is that you read a little about boxing and casting, it would make
you see it clearer , unfortunally I have no link in hand about these
concepts :(

you will have to google for them, or wait until somebody post a link

cheers,
 
Jarod said:
Is t possible to convert object on int with "as" operator ? If yes how to ?

No, "as" only applies to reference types.

From the C# language specification:

<quote>
In an operation of the form e as T, e must be an expression and T must
be a reference type.
</quote>
 
hi Jon,


Good aclaration :)


cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
 
Back
Top