Int32.Parse(String) Method is used to convert the string representation of a number to its 32-bit signed integer equivalent.
Syntax:
public static int Parse (string str);
Here, str is a string that contains a number to convert. The format of str will be [optional white space][optional sign]digits[optional white space].
Return Value: It is a 32-bit signed integer equivalent to the number contained in str.
Exceptions:
- ArgumentNullException: If str is null.
- FormatException: If str is not in the correct format.
- OverflowException: If str represents a number less than MinValue or greater than MaxValue.
Below programs illustrate the use of above-discussed method:
Example 1:
using System;
class GFG {
public static void Main()
{
checkParse( "2147483647" );
checkParse( "214,7483,647" );
checkParse( "-2147483" );
checkParse( " 2183647 " );
}
public static void checkParse( string input)
{
try {
int val;
val = Int32.Parse(input);
Console.WriteLine( "'{0}' parsed as {1}" , input, val);
}
catch (FormatException) {
Console.WriteLine( "Can't Parsed '{0}'" , input);
}
}
}
|
Output:
'2147483647' parsed as 2147483647
Can't Parsed '214,7483,647'
'-2147483' parsed as -2147483
' 2183647 ' parsed as 2183647
Example 2: For ArgumentNullException
using System;
class GFG {
public static void Main()
{
try {
checkParse( null );
}
catch (ArgumentNullException e) {
Console.Write( "Exception Thrown: " );
Console.Write( "{0}" , e.GetType(), e.Message);
}
catch (FormatException e) {
Console.Write( "Exception Thrown: " );
Console.Write( "{0}" , e.GetType(), e.Message);
}
}
public static void checkParse( string input)
{
int val;
val = Int32.Parse(input);
Console.WriteLine( "'{0}' parsed as {1}" , input, val);
}
}
|
Output:
Exception Thrown: System.ArgumentNullException
Reference:
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
12 Jun, 2019
Like Article
Save Article