Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Beginners question

Status
Not open for further replies.

lfc77

Programmer
Aug 12, 2003
218
GB
I'm pretty new to C# and I would like to know, what is the difference between (string)variable and Convert.ToString(variable)? Is it that unless 'checked is used in the first case then no error will be thrown?


 
convert.tostring(variable) parses as a string, (string)variable just casts. most objects and primitives won't cast. casting is gerally just for converting number formats ( (int)myDouble ), or pointing out an object that is higher level than perhaps a return value suggests ( (Panel)myForm ).
 
I'm of the opinion that casting should only be used sparingly - like when you need to coerce an object into another type that is in it's inheritance tree. Like casting a Form object into a Control object (which is OK, because Form inherits from Control).

Other uses would be to truncate a numeric conversion (double to an int, like seanbo showed), but even then I would lean towards using the appropriate Convert method.

Chip H.


If you want to get the best response to a question, please check out FAQ222-2244 first
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top