Parse string to int value
In this chapter you will learn:
- Int Parsing
- Converts string to integer and catch FormatException
- Parse and catch OverflowException
- Convert string value to integer by using the int.TryParse
- 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:
Home » C# Tutorial » Byte, Integer, Long