C# Int16 TryParse(String, Int16)
Description
Int16 TryParse(String, Int16)
converts the string representation
of a number to its 16-bit signed integer equivalent. A return value indicates
whether the conversion succeeded or failed.
Syntax
Int16.TryParse(String, Int16)
has the following syntax.
public static bool TryParse(
string s,
out short result
)
Parameters
Int16.TryParse(String, Int16)
has the following parameters.
s
- A string containing a number to convert.result
- When this method returns, contains the 16-bit signed integer value equivalent to the number contained in s, if the conversion succeeded, or zero if the conversion failed. The conversion fails if the s parameter is null or String.Empty, is not of the correct format, or represents a number less than MinValue or greater than MaxValue. This parameter is passed uninitialized.
Returns
Int16.TryParse(String, Int16)
method returns true if s was converted successfully; otherwise, false.
Example
The following example calls the Int16.TryParse(String, Int16)method with a number of different string values.
using System;/*w w w . j av a 2s .c o m*/
public class StringParsing
{
public static void Main()
{
TryToParse(null);
TryToParse("12345");
TryToParse("1234.0");
TryToParse("16,667");
TryToParse(" -123 ");
TryToParse("+1234");
TryToParse("(123);");
TryToParse("01FA");
}
private static void TryToParse(string value)
{
short number;
bool result = Int16.TryParse(value, out number);
if (result)
{
Console.WriteLine("Converted '{0}' to {1}.", value, number);
}
else
{
if (value == null) value = "";
Console.WriteLine("Attempted conversion of '{0}' failed.", value);
}
}
}
The code above generates the following result.