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 string1
is null, whereas the second will throw NullReferenceException
in that case. An alternative in order to preserve the Equals
call but avoiding this problem is to call the static object.Equals(object, object)
method:
if (object.Equals(string1, string2))
Personally I'd just use ==
in cases where the compile-time types are appropriate though.