C# testing to see if a string is an integer?
Solution 1:
Use the int.TryParse method.
string x = "42";
if(int.TryParse(x, out int value))
// Do something
If it successfully parses it will return true, and the out result will have its value as an integer.
Solution 2:
If you just want to check type of passed variable, you could probably use:
var a = 2;
if (a is int)
{
//is integer
}
//or:
if (a.GetType() == typeof(int))
{
//is integer
}
Solution 3:
I think that I remember looking at a performance comparison between int.TryParse and int.Parse Regex and char.IsNumber and char.IsNumber was fastest. At any rate, whatever the performance, here's one more way to do it.
bool isNumeric = true;
foreach (char c in "12345")
{
if (!Char.IsNumber(c))
{
isNumeric = false;
break;
}
}