tags:

views:

383

answers:

4

I Have some confusion while using Convert.Int32() and int32.Parse(). When we use Convert.Int32() or int32.Parse()...

+12  A: 

Convert.ToInt32() will attempt to convert anything - be it char, double, object, what have you - into an Int32. Int32.Parse() only works for strings.

EDIT: In response to OP's comment, I have a quote taken from this thread:

Basically the Convert class makes it easier to convert between all the base types.

The Convert.ToInt32(String, IFormatProvider) underneath calls the Int32.Parse. So the only difference is that if a null string is passed to Convert it returns 0, whereas Int32.Parse throws an ArgumentNullException.

It is really a matter of choice whichever you use.

Matthew Jones
http://arun-ts.blogspot.com/2008/05/convertint32-vs-int32parse.html
madcolor
You might also want to note caveats.. for instance: `Convert.ToInt32('9')` will result in 57 (the ascii value) where as `Convert.ToInt32("9")` will result in 9. If there is an implicit conversion then the conversion will be used.
Quintin Robinson
Hi,Matthew. If I have a string value and need to convert it into the integer value then which is best to use...
Vijjendra
If you have a string use parse or tryParse.
tster
@Vijj int.TryParse(...) if you cannot guarantee your strings are integers.
mxmissile
There is any performance based difference..
Vijjendra
@@ Vijj Go out for a walk , than come back and checkout the relative similar entry http://stackoverflow.com/questions/641304/any-performance-difference-between-int-parse-and-convert-toint :)
Monu
+2  A: 

Convert.ToInt32 will convert null into 0; Int32.Parse will throw an exception if you pass it null. Also, as Matthew Jones said, Int32.Parse only works for strings.

See this article for more information

Jacob
+4  A: 

Expanding on Matthew's answer.

Convert.ToInt32 allows for user defined conversions in an extendable manner. For any non-predefined conversion (mostly primitives), The Convert class will check and see if the type implements IConventible and if so use it to allow the object to define it's own conversion to Int32 (and many other types).

JaredPar
A: 

According to MSDN Parse() is used for string to int where Convert is much more versatile for conversions.

Int32.Parse()

Convert.Int32() should be your main choice

stewsha