Ali
Ali

Reputation: 927

C# Console.WriteLine Weird

Here is a simple script in C# which outputs two different things. The issue is not about comparing the objects - don't get misguided. This is about using Console.WriteLine to send an output.

var a = "hello";
var b = string.Copy(a);

Console.WriteLine($"a == b: {a == b}");
Console.WriteLine("a == b:" + a == b);

The first Console.WriteLine outputs a == b: True and the second one outputs False which means ignoring the part in the quotation ("a == b:").

I am using VS 2015 and C# 4.5.2 - tested with 4.6 still the same result.

Any idea about this behavior highly appreciated.

Upvotes: 0

Views: 284

Answers (3)

Tim Schmelter
Tim Schmelter

Reputation: 460018

The == operator has a lower precedence than the + operator. That means that first "a == b:" is concatenated(+) with a and then the result is compared(==) with b which returns False.

See: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/

Additive operators are higher than equality operators, so they have a higher precedence .

You could force it with (), in the following code a == b is evaluated first:

Console.WriteLine("a == b:" + (a == b));

Your first example is using string interpolation where the whole expression is evaluated before ToString is called and then the result is concatenated with the rest.

Upvotes: 8

Steve Harris
Steve Harris

Reputation: 5109

The second line is evaluating:

"a == b:" + a == b

And correctly returning False. I.E.

( "a == b:" + a ) == b

So the string is being built as a == b:hello' and being compared to 'hello' as the+operation is done before the==`

You can resolve this by putting brackets around the a == b

Console.WriteLine("a == b:" + (a == b));

Upvotes: 6

Ross Miller
Ross Miller

Reputation: 646

Your second line is 'string literal + a' == b, which will be false. In essence you are doing

"a == b:hello" == b

Which is always going to return false.

Upvotes: 0

Related Questions