Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this not compile in C#?

Tags:

c#

.net

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'

like image 208
superlogical Avatar asked May 05 '11 15:05

superlogical


3 Answers

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.

like image 175
CodesInChaos Avatar answered Nov 05 '22 20:11

CodesInChaos


Because in the second case you try to compile such code:

 if ("xx" + true)
 {
 }
like image 34
Antony Blazer Avatar answered Nov 05 '22 22:11

Antony Blazer


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.

like image 36
Kyle Trauberman Avatar answered Nov 05 '22 20:11

Kyle Trauberman