Sobes.tech
Junior — Middle

How is the comparison of two classes carried out in object-oriented programming?

sobes.tech AI

Answer from AI

In object-oriented programming, comparing two classes usually means comparing their instances (objects). In C#, this can be done by overriding the Equals and GetHashCode methods, as well as implementing the IEquatable<T> interface.

Comparison can be:

  • Reference comparison — checks whether two variables point to the same object.
  • Value comparison — checks whether the internal data of the objects are equal.

Example of overriding Equals and GetHashCode:

class Person : IEquatable<Person>
{
    public string Name { get; set; }
    public int Age { get; set; }

    public override bool Equals(object obj) => Equals(obj as Person);

    public bool Equals(Person other)
    {
        if (other == null) return false;
        return Name == other.Name && Age == other.Age;
    }

    public override int GetHashCode() => HashCode.Combine(Name, Age);
}

You can also override the == and != operators for convenience.

How is the comparison of two classes carried out in… - sobes.tech