C # string.length> 0 is treated as boolean

I am new to C # but not for programming. When I compare the lengths of two lines in the code below, I get an error:

The operator '&' cannot be applied to operands like "bool" and "int"

Apparently string1.Length > 0 considered as a boolean in this context.

How do I make this comparison?

 if (string1.Length > 0 & string2.Length = 0) { //Do Something } 
+4
source share
5 answers

When applied to integers, the & operator in C # is striking AND , not a logical AND . Also = is an assignment, not an equality comparison operator. The expression string1.Length > 0 indeed an expression of Boolean type, while the assignment is an integer (since 0 is an integer).

You need

 if (string1.Length > 0 && string2.Length == 0) 
+8
source

The reason for the error is that you wrote = when you meant == . In c #

 string1.Length > 0 & string2.Length = 0 

means

 (string1.Length > 0) & (string2.Length = 0) 

The left side type is bool , and the right side type is int , which cannot be & -ed together, hence the error. Of course, even if you manage to get past this, Length also cannot be the purpose of the destination.

Use == to verify equality. = - destination.

Consider also using && instead of & . The meaning of x & y is to "evaluate both, the result is true if both are true and false otherwise." The value x && y means "evaluate the left side, if it is false , then the result is false , so do not evaluate the right side. If the left side is true , then act as & ."

+10
source

You probably wanted to do this:

 if (string1.Length > 0 && string2.Length == 0) { //Do Something } 

In C #, the = operator is for assignment only. == used for equality comparisons. You probably also want to use && instead of & ( && will skip the second condition if the first condition evaluates to false).

However, if you really want to "compare string lengths", you can simply do this:

 if (string1.Length > string2.Length) { //Do Something } 
+3
source

This will fix your problem.

 if(string1.Length > 0 && string2.Length == 0) 
0
source

I think you want == for your equality test? Purpose C # returns a value (as in C) .

0
source

Source: https://habr.com/ru/post/1484541/


All Articles