I have this class.
public class Foo { public Guid Id { get; set; } public override bool Equals(object obj) { Foo otherObj = obj as Foo; return otherObj == null && otherObj.Id == this.Id; } public override int GetHashCode() { return this.Id.GetHashCode(); } }
You can see I overrode the Equals and GetHashCode for this object.
Now I run the following snippet of code
// Create Foo List List<Foo> fooList = new List<Foo>(); fooList.Add(new Foo { Id = Guid.NewGuid()}); fooList.Add(new Foo { Id = Guid.NewGuid()}); fooList.Add(new Foo { Id = Guid.NewGuid()}); fooList.Add(new Foo { Id = Guid.NewGuid()}); fooList.Add(new Foo { Id = Guid.NewGuid()}); // Keep Id of last Create Guid id = Guid.NewGuid(); fooList.Add(new Foo { Id = id }); Console.WriteLine('List Count {0}', fooList.Count); // Find Foo in List Foo findFoo = fooList .Where<Foo>(item => item.Id == id) .FirstOrDefault<Foo>(); if (findFoo != null) { Console.WriteLine('Found Foo'); // Found Foo now I want to delete it from list fooList.Remove(findFoo); } Console.WriteLine('List Count {0}', fooList.Count);
When this is run foo is found, but the list doesn’t delete the found item.
Why is this? I thought overrideing the Equals and GetHashCode should fix this?
Is that correct? Shouldn’t it be