Possible Duplicate:
Difference between == operator and Equals() method in C#?
Two forms of equality, the first fails, the second succeeds.
(object)"abc" == (object)"abc"
false
((object)"abc").Equals((object)"abc")
true
In the below reference, we see “Equality operators in C# are not polymorphic”
ref: String Equality operator == in c#
btw: still not sure why this is an issue. I thought it might be something like this, but it isn’t because this test succeeds.
static void Main(string[] args) {
var o = new classOfT<string>() { val = "abc" };
Console.WriteLine((object)o.val == "abc");
}
public class classOfT<T> {
public string val { get; set; }
}
BTW: I DO NOT AGREE WITH THE EXACT DUPLICATE RULING ON THIS QUESTION, BUT HEY.
The Answer states:
… The String class contains both a static bool Equals(string a,
string b) method and a static bool Equals(object a, object b) method.
The difference is that the former is defined within the String class
itself, whilst the latter is inherited from the Object class (which is
the base class of String)
Semantically this makes sense, but does it make sense in the wider context of OO and the C# language?
Why am I bothering with the question? Well, just found a bug, and I’d like to file this in my brain under a rhyme or reason rather than under the “just remember this”, it’s bitten you before category.
Update:
currently thinking about this in terms of working with primitives (from a functional perspective) Vs polymorphism. Since I’ve been doing more and more functional stuff, this is probably why the mother tongue confused me. I’m not done thinking about this yet (no I’m not being pragmatic. I am drawn to language design). Thanks for responding all!
will create an Object reference from the string object. So doing
will create two object references, which are not equal.
However, using the equals method will check to see if the value of the string stored is equal. Again, this is not the default implementation of all objects, but of the String object. For any custom object, you should define your own custom implementation of equals method to achieve this behavior.