Search code examples
c#oopprototypeclone

Object.Equals return false


Object.Equals always return false, Why not equal?

Student student = new Student(3, "Jack Poly");
Student otherStudent = (Student)student.Clone();
if (Object.Equals(student, otherStudent))
{
    Console.WriteLine("Equal");
}
else
 {
    Console.WriteLine("Not Equal");
 }

Clone method like below

    public override StudentPrototype Clone()
    {
        return this.MemberwiseClone() as StudentPrototype;
    }

Solution

  • Look at this article MSDN

    If the current instance is a reference type, the Equals(Object) method tests for reference equality, and a call to the Equals(Object) method is equivalent to a call to the ReferenceEquals method. Reference equality means that the object variables that are compared refer to the same object.

    Your Student is a reference type, The clone MemberwiseClone returns a new other object.

    Student student = new Student(3, "Jack Poly");
    Student otherStudent = (Student)student.Clone();
    

    So the Equal must return false