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
}
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."
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With