Answer the question
In order to leave comments, you need to log in
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
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.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question