I have a Customer class.
public class Customer { private string _id; private string _name; // some more properties follow
I am inheriting the EqualityComparer form MyEqualityComparer(of Customer).
This I am intending to use in LINQ queries.
MyEqualityComparer is intended for partial check between two objects.
If the customer.id and customer.name matches I treat the objects the equal.
public class MyComparer : System.Collections.Generic.EqualityComparer<Customer> { public override bool Equals(Customer x, Customer y) { if (x.Id == y.Id && x.Name == y.Name) return true; else return false; } public override int GetHashCode(Customer obj) { return string.Concat(obj.Id,obj.Name).GetHashCode(); } }
I referred to generating hashcode.
I am little unsure about concatenating strings and using that as a hashcode.
Is this safe and sound what I am trying to do ?
See this question on hashcodes for a pretty simple way to return one hashcode based on multiple fields.
Having said that, I wouldn’t derive from
EqualityComparer<T>myself – I’d just implementIEqualityComparer<T>directly. I’m not sure what valueEqualityComparer<T>is really giving you here, other than also implementing the non-genericIEqualityComparer.A couple more things:
Your present Equals code can be simplified to:
A fuller implementation of Equals might be: