Sobes.tech
Junior — Middle

What is the main purpose of using the Equals method in programming?

sobes.tech AI

Answer from AI

The Equals method in programming is used to check the equality of two objects based on their content, not their reference or memory address. In C#, the Equals method allows you to determine when two objects are considered logically equal.

By default, the Equals method compares references (for reference types), but it is often overridden to compare the values of object fields.

Example of overriding Equals in C#:

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

    public override bool Equals(object obj)
    {
        if (obj is Person other)
        {
            return Name == other.Name && Age == other.Age;
        }
        return false;
    }

    public override int GetHashCode()
    {
        return HashCode.Combine(Name, Age);
    }
}

Thus, the Equals method helps compare objects by their content, which is important for collections, searching, and other operations.