Why does this work:
if ("xx".StartsWith("x"))
{
}
But this doesn't:
if ("xx" + "xx".StartsWith("x"))
{
}
Compiler says error CS0029: Cannot implicitly convert type 'string' to 'bool'
The member access operator .
has higher priority than the +
operator.
Check C# Operators (MSDN) for the C# operator priorities. In particular it lists x.y
as "primary" which is higher than binary +
in "additive".
This means "xx" + "xx".StartsWith("x")
is interpreted as"xx" + ("xx".StartsWith("x"))
and that doesn't compile. It concats a string
and a bool
which gives you a string
. But you can't use a string
as a condition in an if
statement since it's not bool
(and doesn't implement the true
operator either)
It seems you expected it to be interpreted as ("xx" + "xx").StartsWith("x"))
where you first concat the strings and then call StartsWith
on the combined string.
Because in the second case you try to compile such code:
if ("xx" + true)
{
}
Wrap it in Parens
if (("xx" + "xx").StartsWith("x"))
{
}
The reason for the error is that a string
plus a bool
= a string
, and the if statement is expecting a bool
.
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