I\'m just curious as to whether there is something built into either the C# language or the .NET Framework that tests to see if something is an integer
if (x
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;
}
}
its simple... use this piece of code
bool anyname = your_string_Name.All(char.IsDigit);
it will return true if your string have integer other wise false...
This function will tell you if your string contains ONLY the characters 0123456789.
private bool IsInt(string sVal)
{
foreach (char c in sVal)
{
int iN = (int)c;
if ((iN > 57) || (iN < 48))
return false;
}
return true;
}
This is different from int.TryParse() which will tell you if your string COULD BE an integer.
eg. " 123\r\n" will return TRUE from int.TryParse() but FALSE from the above function.
...Just depends on the question you need to answer.
If you only want to check whether it's a string or not, you can place the "out int" keywords directly inside a method call. According to dotnetperls.com website, older versions of C# do not allow this syntax. By doing this, you can reduce the line count of the program.
string x = "text or int";
if (int.TryParse(x, out int output))
{
// Console.WriteLine(x);
// x is an int
// Do something
}
else
{
// x is not an int
}
If you also want to get the int values, you can write like this.
Method 1
string x = "text or int";
int value = 0;
if(int.TryParse(x, out value))
{
// x is an int
// Do something
}
else
{
// x is not an int
}
Method 2
string x = "text or int";
int num = Convert.ToInt32(x);
Console.WriteLine(num);
Referece: https://www.dotnetperls.com/parse