When should I use == and when should I use Equals?

Published 29 March 04 11:56 PM

The Equals method is just a virtual one defined in System.Object, and overridden by whichever classes choose to do so. The == operator is an operator which can be overloaded by classes, but which usually has identity behaviour.

For reference types where == has not been overloaded, it compares whether two references refer to the same object - which is exactly what the implementation of Equals does in System.Object.

Value types do not provide an overload for == by default. However, most of the value types provided by the framework provide their own overload. The default implementation of Equals for a value type is provided by ValueType, and uses reflection to make the comparison, which makes it significantly slower than a type-specific implementation normally would be. This implementation also calls Equals on pairs of references within the two values being compared.

However, the main difference between the two types of comparison in normal use (where you're unlikely to be defining your own value types very often) 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.

So, when should you use which operator? My rule of thumb is that for almost all reference types, use Equals when you want to test equality rather than reference identity. The exception is for strings - comparing strings with == does make things an awful lot simpler and more readable but you need to remember that both sides of the operator must be expressions of type string in order to get the comparison to work properly.

For value types, I'd normally use == for easier-to-read code. Things would get tricky if a value type provided an overload for == which acted differently to Equals, but I'd consider such a type very badly designed to start with.

[Author: Jon Skeet]

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# Mark said on April 16, 2004 10:24 AM:
I thought that structs do not get an implementation of op== by default.
# Jon Skeet said on April 18, 2004 10:35 AM:
Hmm... you're right. I'll amend the article when I'm in a more suitable location...
# Jon Skeet said on April 21, 2004 2:32 AM:
Article modified for correctness - thanks Mark.
# An agglomeration of my thoughts said on April 21, 2004 10:14 AM:
# Vish said on April 24, 2004 10:08 PM:
if this observation is correct then why this shows equality ?

string a="1";
object b="1";
Console.WriteLine(a==b);

Reply me at vkakkar@sisware.com

Thanks!
Vish
# Jon Skeet said on April 26, 2004 1:44 AM:
Because string literals are interned - both a and b are references to the same object. Try this code instead:

string a=new string(new char[]{'1'});
object b=new string(new char[]{'1'});
Console.WriteLine(a==b);
# mrv said on May 19, 2004 4:15 AM:
I am a beginner and would greatly appreciate if you could explain this in more detail:
"Because string literals are interned - both a and b are references to the same object."

What is "interned?"
# avnrao said on May 21, 2004 12:45 AM:
cool blog. just few lines clear lot of doubts.
# Langleyben Leon said on June 23, 2004 1:07 PM:
Identity vs Equivalence
# Langleyben Leon said on June 23, 2004 1:14 PM:
Identity vs Equivalence
# Langleyben Leon said on June 23, 2004 1:15 PM:
Identity vs Equivalence
# ok said on July 18, 2004 12:31 AM:
my web:
http://www.sj55.com/pic_sort http://www.zw88.com/paopaotang.htm http://www.zw88.com/sj.htm http://www.zw88.com/sm/
http://www.zw88.com/sms/ http://www.zw88.com/zw.htm http://www.resou.com/8888.htm http://www.sj55.com/pic/pic_1130.htm
# Eric Joe said on September 16, 2004 2:02 AM:
Ping Back来自:blog.csdn.net
# RebelGeekz said on December 28, 2004 4:54 AM:
[http://itpeixun.51.net/][http://aissl.51.net/][http://kukuxz003.freewebpage.org/][http://kukuxz001.51.net/][http://kukuxz003.51.net/][http://kukuxz005.51.net/][http://kukuxz002.51.net/][http://kukuxz004.freewebpage.org/][http://kukuxz007.51.net/][http://kukuxz001.freewebpage.org/][http://kukuxz006.51.net/][http://kukuxz002.freewebpage.org/][http://kukuxz004.51.net/][http://kukuxz008.51.net/][http://kukuxz009.51.net/][http://kukuxz005.freewebpage.org/][http://kukuxz006.freewebpage.org/][http://kukuxz007.freewebpage.org/][http://kukuxz009.freewebpage.org/]
# Bat's Blog said on February 16, 2005 6:24 PM:
# Living .NET... said on September 7, 2006 2:15 AM:
The notion of identity and equivalence is fundamental, yet very confusing at times. You might end up
# 许晓光 said on October 30, 2007 5:41 AM:

.NETFramework类库提供了静态方法publicstaticboolReferenceEquals(

# protsyk.com » Blog Archive » C# Interview Questions said on November 13, 2007 5:54 AM:

PingBack from http://protsyk.com/cms/?p=140

# C Frequently Asked Questions When should I use and when should I | Cellulite Creams said on June 8, 2009 11:15 PM:

PingBack from http://cellulitecreamsite.info/story.php?id=8552

Leave a Comment

(required) 
(optional)
(required) 

  
Enter Code Here: Required

This Blog

Syndication

Page view tracker