Help with C# statement?

Hey,

i have been messing around with C#. I came across a issue i thought i'd ask here to see anyone could help me. In the picture you can see my issue. i am looking for a way to make more than one argument exception. instead of a bunch of if statements. is there a way i can compile the characters into one if statement? It would really reduce the line count and make it easier for me to track. Thanks.

1 Like

I am pretty sure you could just do "1" "2" "3" etc.

Yep i have tried that and get a error. i thought it might be the way i am calling the if statement by using 'contains'. i will have to go try it again to see (maybe i messed up). thanks for the input. anymore possibilities you know of?

you can do a switch statement. instead of having like 10 or 15 if statements for each argument.

2 Likes

if (int.TryParse(textBox2.Text, out distance))
{
    MessageBox.show("Text only please");
}

No need to write 15 thousand ifs.

Or use

public static bool HasNumber(this string input) {
  return input.Where(x => Char.IsDigit(x)).Any();
}

or with regex

string input = "123 find if this has a number";
bool containsNum = Regex.IsMatch(input, @"\d");
if (containsNum)
{
 //Do Something
}
2 Likes

what is 'out distance' referring to? distance is a error for me. a new class?

It's an int: https://msdn.microsoft.com/en-us/library/system.int32.tryparse.aspx you might want to use the second method I wrote above.

ok, thanks very much

Thanks everyone for your input i appreciate it.

The LINQ query can be simplified even more to:

public static bool HasNumber(this string input) {
  return input.Any(x => Char.IsDigit(x));
}

Keep in mind when creating extensions the class also has to be public and static.