Pitfalls of Equality

February 16, 2008

Consider the fallowing example:

SomeClass class1 = new SomeClass();
SomeClass class2 = new SomeClass();

bool result = (class1 == class2);

Due to class1 and class2 are exactly the same, you should expect result == true. However, result is false. The reason is operator (==) actually compares references of the objects, rather the objects itself. In case you want to compare objects, override and/or use ‘Equals’ method. Some points of interest:

  • By default, Equals method calls to GetHashCode() method and then compares it.
  • string type is immutable, itĀ overrides == operator and inside it calls to actual string comparison.
  • Interlocked.CompareExchange method comparing objects by references (!!)
  • If anyone cares, in Java operator (==) works in same way

Entry Filed under: General C#. .

Leave a Comment

hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


Categories

Top Posts

Tags

.NET addin app.config ArrayList bug CAB Configuration ConfigurationManager ConfigurationSection ContentControl ContextMenu CTime; DateTime custom keys DataBinding DataContext Data templates debugging equals gethashcode GUI Hashtable interlocked Invoke lock lock free memcpy MFC multithreading multithreading; lock free override performance SCSF serialization Smart Client Software Factory Styles System.Configuration unsafe virtual functions Visual Studio wait free WinAPI WinForms WinForms\WPF Integration World of Warcraft World of Warcraft; Addon

Archives