views:

122

answers:

1

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?

+8  A: 
return otherObj == null && otherObj.Id == this.Id;

Is that correct? Shouldn't it be

return otherObj != null && otherObj.Id == this.Id;
BFree
That is exactly the error. Thanks much. Dumb mistake.
David Basarab
:) Happens to all of us...
BFree
"Aw, sounds like someone has a case of the Mondays!" -- Mimi, Office Space
R. Bemrose