Home > Back-end >  How to improve logic if any of 3 values are false then enter the code block?
How to improve logic if any of 3 values are false then enter the code block?

Time:03-11

I have 3 bool variables. I am using Int.TryParse to parse the values of these variables. I would like to develop a condition if any of the 3 values are false then enter the IF code block, but if all 3 values are true, then don't enter the IF block.

How should I specify this condition in c#?

bool var1 = int.TryParse("23", out k);
bool var2 = int.TryParse("Ask", out j);
bool var3 = int.TryParse("45", out i);

CodePudding user response:

I hope that I've got your question right. This is how the condition could look like.

if (!int.TryParse("23", out k) || 
                !int.TryParse("Ask", out j) || 
                !int.TryParse("45", out i)) {
                Console.WriteLine("Can't parse.");
            }
            else{
                Console.WriteLine($"{k} {j} {i}");
            }
         
    
            

CodePudding user response:

(Suggesting this based on OP's comment I don't need the parsed values, I need to check whether any of 3 parsed values is false.)


If you could keep your strings in an array and don't care about the parsed values (or which of the strings are in fact parseable), you could do as follows:

string[] strings = new[] { "23", "Ask", "45" };

var allAreParseable = strings.All(str => int.TryParse(str, out _));

if (!allAreParseable)
{
    Console.WriteLine("Not all values could be parsed");
}
  • Related