简体   繁体   中英

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.

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://docs.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.

The second line is evaluating:

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

And correctly returning False. IE

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM