Home > Back-end >  Outputting a bool to the Console
Outputting a bool to the Console

Time:10-09

This is an easy question I think :-)

Have a look at this program:

string v1 = "Hallo";
string v2 = "Hallo";

Console.WriteLine("Output"   v1 == v2);

This just outputs the following:

False

But if I write:

Console.WriteLine("Output"   true);

It outputs:

OutputTrue

I would think that "v1 == v2" evualuates to "true" and is therefore the same. But I am obviously wrong.

Can anyone explain this behaviour to me? I expected to get the same result (OutputTrue) in both cases. What is happening in the first case?

CodePudding user response:

It firsts adds v1 to "Output" so you'll get the following statement:

Console.WriteLine("OutputHallo" == v2);

To fix this you can add parenthisis:

Console.WriteLine("Output" (v1 == v2));

CodePudding user response:

Reference types are checked whether same references point to the same object in memory, not the value itself.

Although string is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references. This behavior is overridden for strings in c#. https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/reference-types

  •  Tags:  
  • c#
  • Related