Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# string.length > 0 seen as boolean

Tags:

c#

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

Operator '&' cannot be applied to operands of type 'bool' and 'int'

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

How should I perform this comparison?

if (string1.Length > 0 & string2.Length = 0)
{
    //Do Something
}
like image 589
user2453681 Avatar asked Nov 29 '22 12:11

user2453681


2 Answers

The reason for the error is because you have written = when you meant ==. In C#

string1.Length > 0 & string2.Length = 0

means

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

The type of the left side is bool and the type of the right side is int, which cannot be &-ed together, hence the error. Of course even if you managed to get past that, Length cannot be the target of an assignment either.

Use == to test for equality. = is assignment.

Consider also using && instead of &. The meaning of x & y is "evaluate both, the result is true if both are true and false otherwise". The meaning of x && y is "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 proceed as & does."

like image 129
Eric Lippert Avatar answered Dec 05 '22 03:12

Eric Lippert


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

What you need is

if (string1.Length > 0 && string2.Length == 0)
like image 31
Sergey Kalinichenko Avatar answered Dec 05 '22 02:12

Sergey Kalinichenko