Difference between Int32.Parse, Convert.ToInt32 and Int32.TryParse
In C#, we have different options to parse integer values. Amongst these, the Parse
, TryParse
and Convert
options are the most common and have subtle differences in their usage.
I’ll discuss each of these with a short console program.
Int32.Parse(string)
This converts the string representation of a number to its 32 bit signed integer equivalent.
- When
string
isnull
-> throwsArgumentNullException
- When
string
has a non integer value -> throwsFormatException
- When
string
represents a number less thanMinValue
or greater thanMaxValue
-> throwsOverflowException
Example
Convert.ToInt32(string)
This too converts the string representation of a number to its 32 bit signed integer equivalent. This internally calls the Int32.Parse() method.
- When
string
isnull
-> returns 0 - When
string
has a non integer value -> throwsFormatException
- When
string
represents a number less thanMinValue
or greater thanMaxValue
-> throwsOverflowException
Example
Int32.TryParse(string, out int)
This too converts the string representation of a number to its 32 bit signed integer equivalent.
- If integer parsed successfully -> returns
true
and sets the integer in theout
parameter. -
If integer parsing is unsuccessful -> returns
false
and sets the integer in theout
parameter to 0. - When
string
isnull
->out
variable has 0 - When
string
has a non integer value ->out
variable has 0 - When
string
represents a number less thanMinValue
or greater thanMaxValue
->out
variable has 0
Example
Usually the order of preference amongst these is …
Int32.TryParse
> Convert.ToInt32
> Int32.Parse
Hope this was useful!
Leave a Comment