Sobes.tech
Junior — Middle

How is the comparison of different data structures carried out?

sobes.tech AI

Answer from AI

In C#, the comparison of data structures depends on the data type and how the comparison is implemented:

  • Primitive types (int, double, bool, etc.) are compared by value.
  • Structs (value types) are compared by value by default — all fields are compared sequentially.
  • Classes (reference types) are compared by reference, meaning whether they point to the same object.
  • To compare the contents of classes, you usually override Equals() and GetHashCode(), or implement IEquatable<T>.
  • For collections, you can use LINQ methods like SequenceEqual for sequences.

Example of comparing two structs and classes:

struct PointStruct
{
    public int X, Y;
}

class PointClass
{
    public int X, Y;
    public override bool Equals(object obj)
    {
        if (obj is PointClass other)
            return X == other.X && Y == other.Y;
        return false;
    }
    public override int GetHashCode() => (X, Y).GetHashCode();
}

var a = new PointStruct { X = 1, Y = 2 };
var b = new PointStruct { X = 1, Y = 2 };
Console.WriteLine(a.Equals(b)); // True - value comparison

var c = new PointClass { X = 1, Y = 2 };
var d = new PointClass { X = 1, Y = 2 };
Console.WriteLine(c.Equals(d)); // True - because of override
Console.WriteLine(ReferenceEquals(c, d)); // False - different objects
How is the comparison of different data structures… - sobes.tech