Int16.Parse(String) Method in C# with Examples
Last Updated :
12 Jun, 2019
Int16.Parse(String) Method is used to convert the string representation of a number to its 16-bit signed integer equivalent.
Syntax:
public static short 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 16-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( "14321" );
checkParse( "15,784" );
checkParse( "-4589" );
checkParse( " 456" );
}
public static void checkParse( string input)
{
try {
short val;
val = Int16.Parse(input);
Console.WriteLine( "'{0}' parsed as {1}" , input, val);
}
catch (FormatException)
{
Console.WriteLine( "Can't Parsed '{0}'" , input);
}
}
}
|
Output:
'14321' parsed as 14321
Can't Parsed '15,784'
'-4589' parsed as -4589
' 456' parsed as 456
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)
{
short val;
val = Int16.Parse(input);
Console.WriteLine( "'{0}' parsed as {1}" , input, val);
}
}
|
Output:
Exception Thrown: System.ArgumentNullException
Reference:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...