N
N
Nikita Tikhomirov2018-09-12 00:13:42
C++ / C#
Nikita Tikhomirov, 2018-09-12 00:13:42

Why is this string comparison not equal to the same string after string.Format()?

Why will True True True False be printed to the console? (*Why are the second and fourth values ​​not the same?)

static void Main(string[] args)
 { 
            var client = "1 2";
            var broker = "1 " + "2";
            var agent = string.Format("{0} {1}", "1", "2");

            Console.WriteLine(broker);
            Console.WriteLine(agent);
            Console.WriteLine("{0}, {1}, {2}, {3}",

            client == broker,
            (object)client == (object)broker,
            agent == client,
            (object)agent == (object)client);
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Meloman19, 2018-09-12
@Dexter_Legseto

Because string comparison and object comparison are different things.
String is compared character-by-character, as it should be, while object's instance references are compared.
The compiler references the client and broker variables for optimization to the same string instance, so comparing them as object returns True. In the case of agent, a new instance of string is created (Format calls new string()), so comparing them as object returns False.

F
freeExec, 2018-09-12
@freeExec

If you need to search for the same lines and not generate new ones, then you can replace it with

var agent = string.Intern(string.Format("{0} {1}", "1", "2"));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question