Possible Duplicate:
C#: String.Equals vs. ==
Are string.Equals() and == operator really same?
sometimes in a condition between two strings, I write:
if(string1==string2) //Do something
and sometimes I write:
if(string1.Equals(string2)) //Do something
The problem is sometimes the first one doesn’t work, or miswork, is there any difference between the two expressions?
The first one will always work so long as the compile-time type of both operands is
string.If the compile-time type of either operand is anything other than
string, it will use the normal reference identity comparison, rather than comparing strings for equality. Basically you want to call the==(string, string)overload instead of the normal==(object, object)overload.Note that the first will succeed even if
string1is null, whereas the second will throwNullReferenceExceptionin that case. An alternative in order to preserve theEqualscall but avoiding this problem is to call the staticobject.Equals(object, object)method:Personally I’d just use
==in cases where the compile-time types are appropriate though.