0

I have this piece of code which i simplified from my app. It does what I want but I know its not put in the most efficient way because I'm still having some trouble understanding the && and & operators.

if (AgeInput.Text.Equals(""))
{
    Textblock1.Text = "✘";
}
else if (AgeInput.Text.All(Char.IsNumber)){
    Textblock1.Text = "✔";
    //DO-THIS-A
}
else
{
    Textblock1.Text = "✘";
}

I need it to make sure there is no white spaces in the string and to also check so its not empty and finally check if its a number, If it ticks all those requirements it will //DO-THIS-A

Whats the most efficient way to do this?

EDIT: If somebody knows how to make a XAML textbox numerical only (so no whitespaces) that would be even better (only a single property or don't worry otherwise)

mateos
  • 1,405
  • 1
  • 17
  • 26
  • Premature optimizations won't help to much. – Yuval Itzchakov Oct 11 '15 at 12:42
  • Possible duplicate of [How do I get a TextBox to only accept numeric input in WPF?](http://stackoverflow.com/questions/1268552/how-do-i-get-a-textbox-to-only-accept-numeric-input-in-wpf) – mcserep Oct 11 '15 at 12:48

2 Answers2

2
if(!String.IsNullOrEmpty(AgeInput.Text) && AgeInput.Text.All(char.IsNumber))
    Textblock1.Text = "✔";
else
    Textblock1.Text = "✘";

String.IsNullOrEmpty returns true if the input is as stated: Null or Empty.

We Invert that with the "!", so that it returns true if it isn't empty.

Then we add the && Operator to expand the if condition and ask if the text only contains numbers.

Also look here: For a description of the difference between &, && and |, ||

Community
  • 1
  • 1
  • Yes thankyou, I thought I had to use a ! operator somewhere but I did not know where to place it. I knew about `String.IsNullOrEmpty` but didnt see a need to use it as `"" `worked either way – mateos Oct 11 '15 at 12:51
0

Not really sure I understand your question, because && and & are for totally different uses.

if (string.IsNullOrWhiteSpace(AgeInput.Text))
{
    Textblock1.Text = "✘";
}
else if(Char.IsNumber(AgeInput.Text.All))
{
    Textblock1.Text = "✔";
}

The & is a binary operator and && is a logical operator.

user9993
  • 5,833
  • 11
  • 56
  • 117
  • 1
    `&` is also a logical operator in C#; it is perfectly legal to use it on bools. The difference is that `&&` is *lazy* and `&` is *eager*. The lazy operator only evaluates the left hand side if necessary; the eager operator always evaluates both sides. – Eric Lippert Oct 11 '15 at 14:28
  • I had no idea about that, at all! Thanks. – user9993 Oct 11 '15 at 17:49