Why aren't two identical items equal?

Classes compare by reference. Records compare by value.

Why aren't two identical items equal?

The problem

Same data, not equal.

public class Item{    public string Name;    public int Price;} var a = new Item { Name = "Potion", Price = 5 };var b = new Item { Name = "Potion", Price = 5 }; bool same = a == b;   // false

== on a class asks: is it the same object? Two objects with the same data are still two objects.

The fix

Declare it as data.

A record is a type made for data. It compares by its values, and prints them too.

record→same values=equal

The fix in code

One line.

public record Item( string Name, int Price ); var a = new Item( "Potion", 5 );var b = new Item( "Potion", 5 ); bool same = a == b;   // truestring s = a.ToString();// Item { Name = Potion, Price = 5 }

The properties, the constructor, equality and ToString are all written for you.

Going further

Change one value with with.

var sale = a with { Price = 3 };// a is still 5. sale is a new Item at 3.

This kind of record is read only. with makes a copy that has your change.

Watch out in Unity

Records need one extra class.

// once, anywhere in your projectnamespace System.Runtime.CompilerServices{    internal static class IsExternalInit { }}

Unity doesn't ship this type, so records won't compile without it. And Unity's serializer can't save records.

The rule

Just data? Make it a record.

Declare
record Item( ... )
Compare
by value
Change one
item with { Price = 3 }