-3

How to check the string is number or not. I am verifying mobile number codes in which it should have 10 digits and only in numerical format.

string str="9848768447"
if(str.Length==10 &&  Here I need condition to check string is number or not)
{
 //Code goes here
}

I am new to programming. please help me

user3737835
  • 29
  • 1
  • 7

1 Answers1

6

Use int.TryParse:

int i;
if(str.Length==10 && int.TryParse(str, out i))
{
     //Code goes here
}

Another way which has issues with unicode digits is using Char.IsDigit:

if(str.Length==10 && str.All(Char.IsDigit))
{

}
Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • 2
    "which has issues with unicode digits" why even show it then D: – EaterOfCode Jun 24 '14 at 08:39
  • 1
    you could use regex as well `Regex.IsMatch(input, @"^\d+$")` or `Regex.IsMatch(input, @"\d")` – string.Empty Jun 24 '14 at 08:40
  • Wouldn't a `RegEx` solution be more efficient? – Elad Lachmi Jun 24 '14 at 08:40
  • @EaterOfCode: because it can be useful, is efficient and the direct answer to OP's question. It is - by the way - similar to regex with the digit specifier but more efficient and readable. – Tim Schmelter Jun 24 '14 at 08:41
  • @TimSchmelter not really, It's obvious (imo) that he is stating latin numbers and not arabic ones or other weird numeric characters. but hey whatever floats your boat, or integer from that perspective. – EaterOfCode Jun 24 '14 at 08:44
  • @EaterOfCode: it has also the same issues than a regex solution and only if you have weird characters like `۵` which also represent digits. I don't know which culture OP uses (or the users). A telephone number is also not necessarily an `int`. – Tim Schmelter Jun 24 '14 at 08:55