Reputation: 1113
I am preparing for certification on C# and face the following question (code edited for simplicity):
class Class
{
public string Name { get; set; } = "hello";
}
...
Class a = new Class();
Class b = new Class();
Class c = a;
Assert.IsTrue(a.Name == b.Name);
Assert.IsTrue(a.Name.Equals(b.Name));
Assert.IsTrue(Object.Equals(a.Name, b.Name));
Assert.IsTrue(a.Name == c.Name);
Assert.IsTrue(a.Name.Equals(c.Name));
Assert.IsTrue(Object.Equals(a.Name, c.Name));
Assert.IsTrue(a.Name == a.Name);
Assert.IsTrue(a.Name.Equals(a.Name));
Assert.IsTrue(Object.Equals(a.Name, a.Name));
All these assert passed.
Dumps of certification tests say that Object.Equals(*.Name, *.Name)
is the right answer and *.Name.Equals(*.Name)
is wrong.
Why?
Upvotes: 1
Views: 136
Reputation: 1972
Object.Equals
first compares object references, then it calls String.Equals
for further equality check.
String.Equals
tests strings for equality. It is invoked with the method name Equals or with the equality operator.
Object.Equals
compares the contents of objects. It first checks whether the references are equal, as does object.ReferenceEquals
. But then it calls into derived Equals methods to test equality further.
Read more explanation about Object.Equals and String.Equals
Upvotes: 1
Reputation: 706
Because x.Name.Equals(y.Name)
will throw NullReferenceException
if x.Name
is null
while Object.Equals(x.Name, y.Name)
will perform a valid comparison
Upvotes: 7