Because the static version of the .Equal
method was not mentioned so far, I would like to add this here to summarize and to compare the 3 variations.
MyString.Equals("Somestring")) //Method 1
MyString == "Somestring" //Method 2
String.Equals("Somestring", MyString); //Method 3 (static String.Equals method) - better
where MyString
is a variable that comes from somewhere else in the code.
Background info and to summerize:
In Java using ==
to compare strings should not be used. I mention this in case you need to use both languages and also
to let you know that using ==
can also be replaced with something better in C#.
In C# there's no practical difference for comparing strings using Method 1 or Method 2 as long as both are of type string. However, if one is null, one is of another type (like an integer), or one represents an object that has a different reference, then, as the initial question shows, you may experience that comparing the content for equality may not return what you expect.
Suggested solution:
Because using ==
is not exactly the same as using .Equals
when comparing things, you can use the static String.Equals method instead. This way, if the two sides are not the same type you will still compare the content and if one is null, you will avoid the exception.
bool areEqual = String.Equals("Somestring", MyString);
It is a little more to write, but in my opinion, safer to use.
Here is some info copied from Microsoft:
public static bool Equals (string a, string b);
Parameters
a
String
The first string to compare, or null
.
b
String
The second string to compare, or null
.
Returns Boolean
true
if the value of a
is the same as the value of b
; otherwise, false
. If both a
and b
are null
, the method returns true
.
==
, but operators are not polymorphic. In this code, the==
operator is invoked on typeobject
, which does an identity comparison instead of a value one. – Slurry==
overload based on the compile-time type of the operands. TheContent
property isobject
. Operators are not virtual, so the default implementation of==
is called, giving a reference equality comparison. With Equals, the call goes to the virtual methodobject.Equals(object)
;string
overrides this method and performs an ordinal comparison on the string content. See msdn.microsoft.com/en-us/library/fkfd9eh8(v=vs.110).aspx and referencesource.microsoft.com/#mscorlib/system/string.cs,507. – Kenner==
has compile-time typeobject
and the right-hand side has compile-time typestring
, then the C# compiler must pick the (problematic, in this case) overloadoperator ==(object, object)
; but it will issue a compile-time warning that it could be unintended. So read the compile-time warnings! To fix the issue and still use==
, cast the left-hand side tostring
. If I remember correctly, the warning text suggests just that. – Tend