C# Int32 TryParse(String, Int32)

Description

Int32 TryParse(String, Int32) converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the conversion succeeded.

Syntax

Int32.TryParse(String, Int32) has the following syntax.


public static bool TryParse(
  string s,
  out int result
)

Parameters

Int32.TryParse(String, Int32) has the following parameters.

  • s - A string containing a number to convert.
  • result - When this method returns, contains the 32-bit signed integer value equivalent of 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

Int32.TryParse(String, Int32) method returns true if s was converted successfully; otherwise, false.

Example

The following example calls the Int32.TryParse(String, Int32) method with a number of different string values.


using System;//from  w  w w . ja  va  2  s .  c  o m

public class StringParsing
{
   public static void Main()
   {
      TryToParse(null);
      TryToParse("123456");
      TryToParse("1234.0");
      TryToParse("16,667");
      TryToParse("   -123   ");
      TryToParse("+1234");
      TryToParse("(123);");
      TryToParse("01FA");
   }

   private static void TryToParse(string value)
   {
      int number;
      bool result = Int32.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.





















Home »
  C# Tutorial »
    System »




Array
BitConverter
Boolean
Byte
Char
Console
ConsoleKeyInfo
Convert
DateTime
DateTimeOffset
Decimal
Double
Enum
Environment
Exception
Guid
Int16
Int32
Int64
Math
OperatingSystem
Random
SByte
Single
String
StringComparer
TimeSpan
TimeZone
TimeZoneInfo
Tuple
Tuple
Tuple
Type
UInt16
UInt32
UInt64
Uri
Version