I have a number of methods where I perform validation – tryParse being one of the main functions i use.
I end up with code like this:
bool isValid = true;
int dealId;
isValid = !int.TryParse(strArr[0], out dealId) ? false : isValid;
DateTime createdOn;
isValid = !DateTime.TryParse(strArr[1], out createdOn) ? false : isValid;
isValid = !tmp.Add(new BookmarkedDeal(userId, dealId, createdOn)) ? false : isValid;
Is there a better way of setting isValid to false only if the result is false?
This depends on what you definition of “better” is, but you can do something like this:
(assuming of course you are returning this from a method, otherwise, you can just set the value of this to a
bool isValidand use it as you did before)&&is called the conditional-AND operator. The basic idea is it will only evaluate far enough to see if the returned value will satisfy the condition(s). So first it will check to see ifint.TryParse()returns a true, if it does, it will checkDateTime.TryParse()and then the following method if it returns true. The beauty of this operator is if any fails, then it knows that it cannot possibly be true and returns a false immediately.(There is also a conditional-OR operator (
||) that acts the same way, but if evaluates only fair enough until it hits atrue, hence making the entire expression true).