I have the following example.
public class Main
{
public Student Student { get; set; }
public override bool Equals(object obj)
{
if (this.GetType() != obj.GetType()) throw new Exception();
return Student.Age == ((Student)obj).Age;
}
}
public class Student
{
public int Age { get; set; }
public Name Name { get; set; }
public override bool Equals(object obj)
{
if (this.GetType() != obj.GetType()) throw new Exception();
return Age == ((Student)obj).Age;
}
}
public class Name
{
public string FirstName { get; set; }
public string LastName { get; set; }
public override bool Equals(object obj)
{
if (this.GetType() != obj.GetType()) throw new Exception();
return FirstName == ((Name)obj).FirstName && LastName == ((Name)obj).LastName;
}
}
when I try and serialize
JsonConvert.SerializeObject(new Main{ ... });
I get different types in the Equals method of the Main type, and I would assume different types in the other Equals method.
The types that I get are, for
this.GetType() // => Main
obj.GetType() // => Student
Why does json act this why, why does it make use of Equals method and how to make it behave as it should ?
this.GetType()will return in theMainclass?Equalsoverrides? If two objects cannot be equal because they are of different types, then they are not equal. That means, in such a casefalseshould be returned instead of throwing exceptions. Note that the type for the parameter ofEqualsisobject, in other words, theEqualsmethod explicitly permits testing for equality between arbitrary objects, including objects of arbitrary, different types...