Using List.Contains()

  • Thread starter Thread starter Brian Pelton
  • Start date Start date
B

Brian Pelton

I feel like I'm about to get in over my head, so before I go off the
deep end I'm hoping someone can point me in the right direction.

I started down the road of using a List<> of an Interface type.

I wanted to be able to use List.Contains() to determine if the List
already has a certain object based on the Name property - which is
defined by the Interface.

Well it didn't work at first, so I read up and found that I need to
override the Equals and == methods. That was pretty easy, but then I
got warnings that I need to override GetHashCode.

Now, here's my fear:

I want to compare based on Name, but Name is a get-able and set-able
property of the classes that implement ISample. There are quite a few
warnings about how the hash code can never change. But with Name being
set-able, I can't be sure it won't change.

I need Name to be get/set-able because the class is deserialized and I
need a parameterless constructor to do that.


So what do I do??? Thanks for any help...

--Brian
 
Brian Pelton said:
I feel like I'm about to get in over my head, so before I go off the
deep end I'm hoping someone can point me in the right direction.

I started down the road of using a List<> of an Interface type.

I wanted to be able to use List.Contains() to determine if the List
already has a certain object based on the Name property - which is
defined by the Interface.

Well it didn't work at first, so I read up and found that I need to
override the Equals and == methods. That was pretty easy, but then I
got warnings that I need to override GetHashCode.

Now, here's my fear:

I want to compare based on Name, but Name is a get-able and set-able
property of the classes that implement ISample. There are quite a few
warnings about how the hash code can never change. But with Name being
set-able, I can't be sure it won't change.

I need Name to be get/set-able because the class is deserialized and I
need a parameterless constructor to do that.

The documentation for GetHashCode makes it virtually impossible to
implement in a meaningful way for mutable objects. Instead of following
the documentation precisely, I would implement GetHashCode so that the
hash code doesn't change while equality doesn't change - in other
words, make sure that if x.Equals(y), then
x.GetHashCode()==y.GetHashCode().

If someone chooses to change the Name of one of your objects while it's
being used as a key in a Hashtable, then they're not going to be able
to find it - but you can make sure that so long as the object *isn't*
changed, it can work as a hash key.

Not everything is naturally a good key for a hashtable, unfortunately -
I believe that making GetHashCode a method on Object rather than
creating an IHashable interface was a mistake, personally. (I'm still
somewhat on the fence about it, admittedly...)
 
Back
Top