Explore Library
Code Quiz

Distinct on Reference Types

A LINQ Distinct call on custom objects returns duplicates because reference types compare by reference.

Codecsharp
class Person
{
    public string Name { get; set; }
}

var people = new List<Person>
{
    new Person { Name = "Alice" },
    new Person { Name = "Alice" },
    new Person { Name = "Bob" }
};

// Intended: remove duplicates by Name
var unique = people.Distinct().ToList();

Console.WriteLine(unique.Count); // expected 2

Why does unique.Count print 3 instead of the expected 2, and how do you fix it?