The World According to Nick
My take on Software, Technology, Politics, and anything else I feel like talking about.
Tuesday, March 30, 2004

C# FAQ: Object.Equals vs. operator == 

When should I use == and when should I use Equals? I actually didn't know this little tidbit... and my first reaction on reading about it was Ewwwwww... Here is the relevant portion:

The main difference between the two is polymorphism. Operators are overloaded, not overridden, which means that unless the compiler knows to call the more specific version, it'll just call the identity version. To illustrate that, here's an example:

using System;

public class Test
{
   static void Main()
   {
      // Create two equal but distinct strings
      string a = new string(new char[] {'h', 'e', 'l', 'l', 'o'});
      string b = new string(new char[] {'h', 'e', 'l', 'l', 'o'});

      Console.WriteLine (a==b);
      Console.WriteLine (a.Equals(b));

      // Now let's see what happens with the same tests but
      // with variables of type object
      object c = a;
      object d = b;

      Console.WriteLine (c==d);
      Console.WriteLine (c.Equals(d));
   }
}

The results are:

True
True
False
True

The third line is False because the compiler can only call the non-overloaded version of == as it doesn't know that the contents of c and d are both string references. As they are references to different strings, the identity operator returns false.


One more time... just for effect... Ewwwwww.

About Me



Name: Nick
Home: Wauwatosa, WI, United States

I'm a Software Consultant in the Milwaukee area. Among various geeky pursuits, I'm also an amateur triathlete, and enjoy rock climbing. I also like to think I'm a political pundit.


 View My Profile

Archives
 Home Page

Subscribe to this Feed

Search Archives
Previous Posts
Writing Around the Garbage Collector
The Outsourcing Bogeyman
More Helpful Messages from MSN Messenger
One More Reason to Interview at Microsoft
E-mail and Snail Mail Unite
Can Blogging Ruin Your Life?
Congress to Test Air Screening Program
Anti-Piracy Vigilantes Strike
It Was All About the Oil... for the French
The Programmer's Secret Handshake

Personal Links
Carnival of the Badger
The Coding Monkey
del.icio.us Links
Flickr Photos
Blog Critics Reviews





Blogroll Me!

music
books
video
culture
politics
sports
gaming

www.flickr.com
This is a Flickr badge showing public photos from Nick_Schweitzer. Make your own badge here.

Credits

Blogcritics: news and reviews







This page is powered by Blogger. Isn't yours?

Weblog Commenting and Trackback by HaloScan.com

RSS-to-JavaScript.com

Listed on BlogShares

Design By maystar