0

As I am making a console application I can't seem to get the .Length to check whether it's empty for an if statement to work, says that it's "read only".

I can't simply define the value as int due to using console to retrieve the data.

Console.Write("Enter your Phone Number:  ");
phone_number = Console.ReadLine();
BartoszKP
  • 34,786
  • 15
  • 102
  • 130
  • Managed to get the length of string as a temp val, still unsure about the only numeric! –  Aug 17 '14 at 09:49
  • see [this](http://stackoverflow.com/questions/894263/how-to-identify-if-a-string-is-a-number) and [this](http://stackoverflow.com/questions/273141/regex-for-numbers-only) – Eli Aug 17 '14 at 09:49

3 Answers3

0

You can use int.TryParse(). It returns true if the string is a valid int. If the string is empty or not numeric it will return false. You didn't mention it in your question so I am assuming you aren't entering in decimal numbers (ie. 34.12).

int phoneNumber;

if(int.TryParse(Console.ReadLine(), out phoneNumber))
{
     // phone number was an int
}
else
{
     // not an int
}
Alex Wiese
  • 8,142
  • 6
  • 42
  • 71
0

That's very simple.

first you check if the string is null or empty using this Method:

String.IsNullOrEmpty(string value)

if the method returned true it means that you should not continue(the string is null or empty).

then you want to check that if the string can be converted to int(number).so you can use:

public static bool TryParse(
string s,
out int result)

If you want to know more about int.TryParse method,you can refer to http://www.dotnetperls.com/int-tryparse for a simple tutorial.

Happy codding. If you have anymore answers,I'm ready here :D

Code Geek
  • 29
  • 4
0

Although not exactly your question, you should use only the digits of your input as a phone number. The format may vary but still be valid:

(+001)555-123456

555 123456

123456

555 12 34 56

All valid answers to the question. Don't make people type their number in ways they never do it. Just accept their input and take what you need:

Console.Write("Enter your Phone Number:  ");
var input = Console.ReadLine();

string phoneNumber = new string(input.Where(char.IsDigit).ToArray());
nvoigt
  • 75,013
  • 26
  • 93
  • 142
  • +1 for user-friendly input – Sergey Berezovskiy Aug 17 '14 at 10:09
  • Is this a valid phone number `०१२७८` ? – Selman Genç Aug 17 '14 at 10:59
  • @Selman22 personally, I'd say no, because I'd have a hard time dialing it. But if it's actually digits and I just don't know how to translate it to arabic numbers, then maybe yes. – nvoigt Aug 17 '14 at 11:12
  • I just took some random numbers from [here](http://www.fileformat.info/info/unicode/category/Nd/list.htm) my point is `char.IsDigit` returns true for all those digits. and I think op most likely wants only latin digits (0-9) – Selman Genç Aug 17 '14 at 11:31