In the code block below I would expect dictCars to contain: { Chevy:Camaro, Dodge:Charger }
But, dictCars comes back empty. Because this line returns false each time it
You need to tell Contains what makes two Car
s equal. By default it will use ReferenceEquals
which will only call two objects equal if they are the same instance.
Either override Equals
and GetHashCode
in your Car
class or define an IEqualityComparer
class and pass that to Contains
.
If two Car
s that have the same CarID
are "equal" then the implementation is pretty straightforward:
public override bool Equals(object o)
{
if(o.GetType() != typeof(Car))
return false;
return (this.CarID == ((Car)o).CarID);
}
public override int GetHashCode()
{
return CarID.GetHashCode();
}