casting and converting

T

Timothy V

string and int are two complety different types. Basically, casting only
works on two compatible (derived) types. A string and an int are no where
near the same. They may look it, but 1 is not "1" by any means. So in order
to 'convert' something to something (in this case, string to int),
Convert.ToInt32() must be invoked.

As far as i know, casting works best in the cases of inheritance and
polymorphism. I can explain your conversion problem more if you have
knowledge in those two areas.

Hope that helps,

Tim (new to C#, but proficient in C++).
 
J

Jon Skeet [C# MVP]

Frazer said:
I am confused when to use (int) and when to use Convert.toint32..
eg here

string s= "1";

int j = (int) s; //this gives me an error and i have to use convert.toint32.
why is that so and how do i know when to use which.

Use casting when either the reference *is* in fact an instance of the
class you're interested in, eg

object x = "hello";
string s = (string)x;

or where there's a conversion available *not* through the libraries,
but through the type itself or the C# language rules (eg SqlString to
String or int to byte).

Use Convert or Parse when neither of these is the case.
 
F

Frazer

hi,
I am confused when to use (int) and when to use Convert.toint32..
eg here

string s= "1";

int j = (int) s; //this gives me an error and i have to use convert.toint32.
why is that so and how do i know when to use which.

thnx
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top