1. Home
  2. Computing & Technology
  3. C / C++ / C#
photo of David Bolton

David's C / C++ / C# Blog

By David Bolton, About.com Guide to C / C++ / C#

Answer to C# Programming Problem (by Robert C. Cartaino)

Wednesday May 21, 2008
The output is:
    False
    True
Why? When comparing two objects, the equality operator (==) checks to see if the objects are exactly the same object (i.e. the same reference) and not two different instances of objects. In the first comparison, to compiler creates two different objects of type int. So, even though the value in each object is the same, the object a and the object b are different objects. So the comparison of these two different instances is False.

In the second comparison, the output is True because c and d refer to string literals. In C#, hard-coded strings with the same value (c = 10, d=10), don't necessarily result in a new string instance being created. A C# compiler in .NET uses something called an intern pool which contains a single reference to each unique literal string declaration in your system. So every time you reference the same string literal, you get a reference to the same string. So the comparison of two objects containing the same literal string results in True.

Comments

No comments yet. Leave a Comment

Leave a Comment

Line and paragraph breaks are automatic. Some HTML allowed: <a href="" title="">, <b>, <i>, <strike>

Explore C / C++ / C#

More from About.com

  1. Home
  2. Computing & Technology
  3. C / C++ / C#

©2008 About.com, a part of The New York Times Company.

All rights reserved.