Monday, March 12, 2012

what is the difference between == and .Equals

Hi guys,

bool b = (object)1 == (object)1; //returns false;

bool b1 = (object)"a" == (object)"a"; //returns true

bool b2 = ((object)1).Equals((object)(1)); //returns true

Could any one explain me why first and second statement has different output??

Thanks in advance,

Maulik

This article should help understand the differences:

http://blogs.msdn.com/csharpfaq/archive/2004/03/29/102224.aspx


int a = 5;
int b = 5;

object oa = a;
object ob = b;

When dealing with reference types (ie objects) the == operator tells you if the objects are actually the same object which they are not

so (oa == ob) is false

Whereas in this instance oa.Equals(ob) is true as it compares the value of the object.


the string object is a special case where == is the same as .Equals

bool b1 = (object)"a" == (object)"a"; //returns true



String class operator == and method Equals are the same. In all other cases "==" compares object's address (must be the same object to be equal) and "Equal" object content

0 comments:

Post a Comment