How to parse string as int in C#?
To parse string as int in C# you can use the built in methodInt32.TryParse()
. The method will take 2 parameters:1- The string value to be parsed.
2- out outputValue: which you should define before the parse.
The method
Int32.TryParse()
will return true
/false
Boolean.Example
using System;
public class Program
{
public static void Main()
{
/* Example of parsing a valid int */
string valueAsString = "1";
int outputValue ;
bool success = Int32.TryParse(valueAsString, out outputValue);
if(success){
Console.WriteLine("Value is int");
}else{
Console.WriteLine("Value is NOT int");
}
/* Example of parsing an invalid int: Float format */
valueAsString = "0.000456";
success = Int32.TryParse(valueAsString, out outputValue);
if(success){
Console.WriteLine("Value is int");
}else{
Console.WriteLine("Value is NOT int");
}
/* Example of parsing an invalid int: non numeric format */
valueAsString = "s";
success = Int32.TryParse(valueAsString, out outputValue);
if(success){
Console.WriteLine("Value is int");
}else{
Console.WriteLine("Value is NOT int");
}
}
}
Output
Value is int
Value is NOT int
Value is NOT int
Value is NOT int
Value is NOT int