First if condition
if(Txt1.Text != "" && Txt2.Text != "")
Second if condition
if((Txt1.Text && Txt2.Text) != "")
Is there any diff between these two cond开发者_运维技巧itional statement?
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.
Um, the second one is mal-typed and is rejected by the compiler?
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.
you cant do the second one. the first one is correct.
the 2nd one is not accepted by the compiler. because the string type can't be compared with boolean type.
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.
精彩评论