C# Console.WriteLine Weird

  • A+

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.

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)); 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: