Parse string to int value

In this chapter you will learn:

  1. Int Parsing
  2. Converts string to integer and catch FormatException
  3. Parse and catch OverflowException
  4. Convert string value to integer by using the int.TryParse
  5. TryParse with while loop

Int Parsing

using System;/*from  ja  v  a 2 s .c o  m*/

class MainClass
{
    public static void Main()
    {
        int value = Int32.Parse("99953");
        Console.WriteLine("{0}", value);
    }
}

The code above generates the following result.

Parse and catch exception

using System;//from  j av a  2  s .  c  o m

public class Main
{
   public static void Main()
   {
      Convert("179");
   }

   private static void Convert(string value)
   {
      try
      {
         int number = Int32.Parse(value);
         Console.WriteLine("Converted '{0}' to {1}.", value, number);
      }
      catch (FormatException)
      {
         Console.WriteLine("Unable to convert '{0}'.", value);
      }
   }
}

Parse and catch OverflowException

using System;/*  j a v a  2  s.  c  o m*/
using System.Globalization;

public class Example
{
   public static void Main()
   {
      string string1 = "2";
      try {
         int number1 = Int32.Parse(string1);
         Console.WriteLine(number1);
      }
      catch (OverflowException) {
         Console.WriteLine("'{0}' is out of range of a 32-bit integer.", string1);
      }
      catch (FormatException) {
         Console.WriteLine("The format of '{0}' is invalid.", string1);
      }

   }
}

Use TryParse

using System;/* j a v a2s  .c  o  m*/
public class MainClass {
    public static void Main() {

        int i;
        bool failure = int.TryParse("qwerty", out i);
        bool success = int.TryParse("123", out i);
    }
}

TryParse with while loop

using System;/*from  j  a v a 2 s  .com*/
using System.Collections.Generic;
using System.Text;

class Program
{
 static void Main(string[] args)
 {
      int numberEntered;
      while(!int.TryParse(Console.ReadLine(), out numberEntered)){
           Console.WriteLine("Please try again");
      }
      Console.WriteLine("You entered " + numberEntered.ToString());
 }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. Use CultureInfo in int.ToString method
Home » C# Tutorial » Byte, Integer, Long
Integer Family
Integer ranges
byte
Convert to byte
Parse string to byte
byte format
byte octal and hexadecimal
byte binary operation
byte overflow with unchecked
int
int value
Compare int value
int calculation
int value overflow
int binary operation
Parse string to int value
Format int value
int in binary, octal and hexadecimal
long
long value calculation
ulong