views:

111

answers:

6

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?

+6  A: 

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.

Blair Conrad
+2  A: 

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

Ira Baxter
+1  A: 

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

Lerxst
+1  A: 

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

sza
+3  A: 

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.

Thomas
Nice point about the Txt1.Text + Txt2.Text. On the other hand, `string.IsNullOrEmpty` isn't necessarily a drop-in replacement - sometimes we really are looking specifically for empty strings. Perhaps `null` stands for uninitialized, and any non-empty value is valid. Although I agree with @Thomas that it's worth using whenever it makes sense.
Blair Conrad
A: 
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), transitive (a=b, b=a) and symmetric (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.

Justin Johnson