Check if a string is a number in C#
To check whether a string is a number is C#, we can use built in methodint.TryParse()
. Example
using System;
public class Example
{
public static void Main()
{
string s1 = "123";
string s2 = "abc";
int n;
bool isNumber = int.TryParse(s1, out n);
Console.WriteLine(isNumber);
isNumber = int.TryParse(s2, out n);
Console.WriteLine(isNumber);
}
}
Output
True
False
False