The World According to Nick
Politics, News, Photography, and Triathlons... What don't I talk about?
Tuesday, March 30, 2004
<< Writing Around the Garbage Collector Thats a SIDE Effect? >>
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.
# Posted at 9:42 AM by Nick  |  Comment Feed Link No Comments  |  No Trackbacks

 Add to del.icio.us |  Digg this Post | Filed Under: Old Blog

Comments are closed.


© Copyright 2012 Nick Schweitzer
Powered By newtelligence dasBlog 1.9.7067.0
Theme Based on Design By maystar