Thursday, July 9, 2009
Difference between Int32.Parse(), Convert.ToInt32 and Int32.TryParse()
Int32.Parse Method
-Converts the string representation of a number to its 32-bit signed integer equivalent.
-When s is a null reference, it will throw ArgumentNullException.
-If s is other than integer value, it will throw FormatException.
-When s represents a number out of range, it will throw OverflowException.
Example Program
int quantity;
try
{
quantity = int.Parse(txtQuantity.Text);
}
catch (FormatException)
{
quantity = 0;
}
catch (OverflowException)
{
quantity = 0;
}
Convert.ToInt32(string)
-Converts the specified string representation of 32-bit signed integer equivalent. This calls in turn Int32.Parse () method.
-When s is a null reference, it will return 0 rather than throw ArgumentNullException.
-If s is other than integer value, it will throw FormatException.
-When s represents a number out of range, it will throw OverflowException.
Int32.TryParse Method
-Converts the specified string representation of 32-bit signed integer equivalent to out variable, and returns true if it is parsed successfully, false otherwise.
-When s is a null reference, it will return 0.
-If s is other than an integer value, the out variable will have 0.
-When s represents a number out of range, the out variable will have 0.
int quantity;
if (int.TryParse(txtQuantity.Text, out quantity) == false)
{
quantity = 0;
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment