I have a condition in a silverlight application that compares 2 strings, for some reason when I use ==
it returns false while .Equals()>
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
.