Isn’t it funny how the “easiest” concepts can be the most complicated? A reader sent me the following quiz to help us appreciate the subtlies of equality in the system. Luckily he gave me the answers as well… ;-)
Consider the following program:
object x = new object();
object y = new object();
/*Question 1*/ Console.WriteLine(x == y && !x.Equals(y));
/*Question 2*/ Console.WriteLine(x != y && x.Equals(y));
/*Question 3*/ Console.WriteLine(x == y);
/*Question 4*/ Console.WriteLine(x == y && (object)x != (object)y);
They should all print “false” right?
For each question, find a way to declare and initialize x and y such that:
Question 1: prints true
Question 2: prints true
Question 3: does not even compile
Question 4: prints true
Notice, we are not asking for a solution that works for all 4, one solution for each will be fine…
All answers should be of the form:
public static void Question<<question number>>()
{
<<type>> x = <<intialize instance>>;
<<type>> y = <<intialize instance>>;
Console.WriteLine(<<question>>);
}
So for example, a legal (but incorrect) answer to question1 would be:
public static void Question1()
string x = "1";
object y = new Object() ;
Console.WriteLine(x == y && !x.Equals(y));
The rules of the game: