why the Clist.Contains(customer) is not getting true in that case ?

why the Clist.Contains(customer) is not getting true while the new object that i created is already on the list dose that means that i have to override the Equals method in the customer class
c#

            List<Customer> Clist = new List<Customer>(2) 
            {
                new Customer() { Id = 1, Name = "mina" },
                new Customer() { Id = 2, Name = "shaker" },
                new Customer() { Id = 3, Name = "Kirollos" },
                new Customer() { Id = 4, Name = "georget" }
            };

            Customer customer = new Customer() { Id = 1, Name = "mina" };


            if (Clist.Contains(customer))
            {
                Console.WriteLine("Customer Exits");
            }
            else 
            {
                Console.WriteLine("customer is not in the list");
            }

i have tried to override the Equals() method in the customer class but, what was intersting is that it works
c#
    public class Customer
    {
        public int Id { get; set; }
        public string? Name { get; set; }

        public override bool Equals(object? obj)
        {
            if (obj == null) return false;
            if (obj.GetType() != typeof(Customer)) return false;
            return (this.Name == ((Customer)obj).Name && this.Id == ((Customer)obj).Id); 
        }

        public override int GetHashCode()
        {
            return this.Id.GetHashCode();
        }
    }
Was this page helpful?