FAQ : “==” or .Equals() ?


It is I would use the a very simple example used on MSDN Blog post.


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));
	}
}

Output :

True
True
False
True

References :

So, My rule of thumb is that for almost all reference types, use Equals when you want to test equality rather than reference identity. I agree that “==” is more readable but .Equals() on other side slightly boosts the performance too

Advertisements

Published by

Aarsh Talati

Software Developer

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s