How to avoid short circuit evaluation in C# while doing the same functionality
Asked Answered
S

2

15

Do we have any operator in C# by which I can avoid short circuit evaluation and traverse to all the conditions.

say

if(txtName.Text.xyz() || txtLastName.Text.xyz())
{

}

public static bool xyz(this TextBox txt)
{
//do some work.
return false;
}

It should evaluate all conditions irrespective of output obtained. And after evaluating last condition continues according to result obtained. ?

Siler answered 14/7, 2010 at 8:2 Comment(2)
Why would you want to evaluate the same condition twice?Happ
@Adrian: Take it as a sample example. xyz function may contain any kind of defination, can be a delegate or something else.Siler
S
27

Just use a single bar, this will evaluated both arguments regardless of the outcome of the first result.

if(txtName.Text.xyz() | txtLastName.Text.xyz()) { }

You can also do the same with AND, i.e. You can replace && with a single ampersand to get the same affect as above:

if(txtName.Text.xyz() & txtLastName.Text.xyz()) { } // Both sides will be called
Soembawa answered 14/7, 2010 at 8:9 Comment(6)
Sorry for the necropost, but this is NOT the correct way to do it. This is calling a different operation, a bitwise and/or, which does require the second function to execute to return an appropriate value. This is cause weirdness if you're returning certain numerical values.Torture
@BennyMackney got an example?Soembawa
Doing something like var a = funcA(); var b = funcB(); if(a || b) will make it much clearer what you're trying to do. If you do it with the single symbol version (the bitwise and/or) you will get weirdness, particularly with and (&). For example, (4&8) == 0, which is false, whereas 4 && 8 is true. Now C# stops this (because you're turning ints into bools without explicitly casting it) but other languages (e.g. Javascript) will operate differently. For example, in my JS console: if(4&8){console.log('this should exec right?');}else if(4&&8){console.log("Wrong!");} VM321:1 Wrong!Torture
@BennyMackney this is a C# question. The OP asked how to call both methods in an if statement and this answer satisfies that. While this answer is correct, I agree that it's not best practice. Best practice would be to call both methods separately for readability and then combine their results into the if statement. Ie bool answerA = funcA(); bool answerB = funcA(). if (answerA && answerB){ // Do something }.Soembawa
I know. But Javascript was also mentioned, and this is a comment and not an actual answer, so I was speaking in a broader sense.Torture
This was just what I needed. Given that @BennyMackney didn't seem to have any rationale for disliking this approach (except in an unrelated language), I'm using it!Bijugate
F
7

Just use a single bar;

if(txtName.Text.xyz() | txtLName.Text.xyz())
{

}
Filippo answered 14/7, 2010 at 8:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.