ACP
ACP

Reputation: 35268

Is there any difference between these two "if" conditional statement?

First if condition

if(Txt1.Text != "" && Txt2.Text != "")

Second if condition

if((Txt1.Text && Txt2.Text) != "")

Is there any diff between these two conditional statement?

Upvotes: 1

Views: 364

Answers (6)

Justin Johnson
Justin Johnson

Reputation: 31300

if((Txt1.Text && Txt2.Text) != "")

While boolean logic does have associative properties for the && and || operators, it does not apply to the equality operator, which is what it looks like you're trying to do here:

(a && b) != ""  -- doesn't translate to --> a != "" && b != ""

Equality, is defined in first-order logic as being reflexive (a=a), symmetric (a=b, b=a) and transitive (a=b, b=c, a=c), but not associative.

Alternatively, if you think about it from the compiler's perspective, parentheses have a higher precedence than the equality operator. So, when the compiler evaluates the expression (Txt1.Text && Txt2.Text) != "", it first evaluates what's inside of the parentheses, and then does the equality check.

Upvotes: 0

Thomas
Thomas

Reputation: 64635

First, as Blair Conrad stated, if((Txt1.Text && Txt2.Text) != "") will not compile as you cannot do a boolean and operation on two strings. However, if you are asking whether if((Txt1.Text + Txt2.Text) != "") is more efficient than the first operation, I would say that it probably is not more efficient for the simple reason that Txt1.Text + Txt2.Text will first create a new string and then compare it against the empty string. Granted, we are probably talking about a difference in nanoseconds.

Regardless, you should use string.IsNullOrEmpty on each of the strings because it makes your intent clearer.

Upvotes: 3

zs2020
zs2020

Reputation: 54514

the 2nd one is not accepted by the compiler. because the string type can't be compared with boolean type.

Upvotes: 1

Greg Olmstead
Greg Olmstead

Reputation: 1551

you cant do the second one. the first one is correct.

Upvotes: 1

Ira Baxter
Ira Baxter

Reputation: 95324

Um, the second one is mal-typed and is rejected by the compiler?

Upvotes: 3

Blair Conrad
Blair Conrad

Reputation: 241754

Yes. The second one is attempting to && two strings, and compare the result to the empty string. I don't believe this is valid C#, as no && operator overload exists for two strings.

I appreciate your desire for terseness, but the first one is really what you want.

Upvotes: 7

Related Questions