How I can check if my string only contain numbers?
I don't remember. Something like isnumeric?
Just check each character.
bool IsAllDigits(string s)
{
foreach (char c in s)
{
if (!char.IsDigit(c))
return false;
}
return true;
}
Or use LINQ.
bool IsAllDigits(string s) => s.All(char.IsDigit);
If you want to know whether or not a value entered into your program represents a valid integer value (in the range of int), you can use TryParse(). Note that this approach is not the same as checking if the string contains only digits.
bool IsAllDigits(string s) => int.TryParse(s, out int i);
You could use Regex or int.TryParse.
See also C# Equivalent of VB's IsNumeric()
Microsoft.VisualBasic namespace. It's not legacy code or anything like that. If it does what you want more easily than the other solutions, use it.int.TryParse or long.TryParse, since they can overflow.int.TryParse() does not throw overflow exceptions. It just returns false.int.TryParse would return false for the value 9876543210, due to overflow. That is, the value "9,876,543,210" is too large to fit in an int.TryParse() would be helpful in that case.int.TryParse() method will return false for non numeric strings
int.TryParse() does not throw an exception if the string is too long or the integer is too big.Your question is not clear. Is . allowed in the string? Is ¼ allowed?
string source = GetTheString();
//only 0-9 allowed in the string, which almost equals to int.TryParse
bool allDigits = source.All(char.IsDigit);
bool alternative = int.TryParse(source,out result);
//allow other "numbers" like ¼
bool allNumbers = source.All(char.IsNumber);