Trivia: Equality of objects and strings

A small trivia question for a change; some of my colleagues and friends may already have heard this from me.

Take a look at the following snippet of C# code:

T x1 = V1;
T x2 = V2;

Console.WriteLine(x1 == x2);
Console.WriteLine(x1.ToString() == x2.ToString());

In the code, you need to fill in three missing parts: Name of a type T, and two values of that type, V1 and V2. T is a reasonably common CLR type (i.e. one of the very basic types in .NET).

The question: For which type and values does the application print True and False? In other words, what is the case when objects’ logical comparison considers them equal, but their string representations differ? There may be multiple answers, and I’m glad to hear some more.

After you have carefully thought about it, you can take a look at one answer. If you have others, please post a comment!

June 30, 2009 · Jouni Heikniemi · 2 Comments
Tags:  Â· Posted in: .NET

2 Responses

  1. Simo - July 3, 2009

    Overload ToString() method to return a random number as a string.

    If you are planning to run it until the universe cools down and don't want a single true-true result, then use instance counter-style static variables.

  2. Jouni Heikniemi - July 3, 2009

    Ok, though that would sort of invalidate the condition of T being a "reasonably common CLR type"…

Leave a Reply