I wrote code below to check entered data from components in a form in C#.
This code calls some function that each return a Boolean value. If check is Ok, the functions return false else they return true.
If my user has not completed any input correctly, the first code check function returns true and the other functions calls are skipped.
How do I avoid skipping the other function calls even when one returns true?
Naming conventions:
- variables starst with ‘txt’ are TextBox
- variables stars with ‘mtxt’ are MaskedTextBox
- variables stars with ‘rtxt’ are RichTextBox
code:
bool allIsOK = false;
allIsOK = checker.txtChecker(txtcode) ;
allIsOK = allIsOK || checker.txtChecker(txtdavar);
allIsOK = allIsOK || checker.txtChecker(txtKomakHazine);
allIsOK = allIsOK || checker.txtChecker(txtnevisande);
allIsOK = allIsOK || checker.txtChecker(txtonvan);
allIsOK = allIsOK || checker.txtChecker(txtostadMoshaver);
allIsOK = allIsOK || checker.txtChecker(txtostadRahnama);
allIsOK = allIsOK || checker.richTextBoxChecker(rtxtmaghale);
allIsOK = allIsOK || checker.mtxtDateChecker(mtxtdefa);
allIsOK = allIsOK || checker.mtxtDateChecker(mtxttasvib);
You’re running into short-circuiting of the expressions; if the first part of an OR (||) is true, evaluation of the second part isn’t necessary. There’s a similar rule for AND (&&), if the first part is false, the second part isn’t evaluated. This is by design and is a very useful characteristic of the language.
The simplest change to your code to ensure all your checks are evaluated would be to swap the order of the tests, putting the check on the left of the
||operator.