1: class Product : IEquatable<Product>
2: {
3: public int ProductId { get; set; }
4: public string Name { get; set; }
5: public string Category { get; set; }
6: public DateTime MfgDate { get; set; }
7: public Status Status { get; set; }
8:
9: public override bool Equals(object obj)
10: {
11: return Equals(obj as Product);
12: }
13:
14: public bool Equals(Product other)
15: {
16: //Check whether the compared object is null.
17: if (ReferenceEquals(other, null)) return false;
18:
19: //Check whether the compared object references the same data.
20: if (ReferenceEquals(this, other)) return true;
21:
22: //Check whether the products' properties are equal.
23: return ProductId.Equals(other.ProductId)
24: && Name.Equals(other.Name)
25: && Category.Equals(other.Category)
26: && MfgDate.Equals(other.MfgDate)
27: && Status.Equals(other.Status);
28: }
29:
30: // If Equals() returns true for a pair of objects
31: // then GetHashCode() must return the same value for these objects.
32: // read why in the following articles:
33: // http://geekswithblogs.net/akraus1/archive/2010/02/28/138234.aspx
34: // http://stackoverflow.com/questions/371328/why-is-it-important-to-override-gethashcode-when-equals-method-is-overriden-in-c
35: public override int GetHashCode()
36: {
37: //Get hash code for the ProductId field.
38: int hashProductId = ProductId.GetHashCode();
39:
40: //Get hash code for the Name field if it is not null.
41: int hashName = Name == null ? 0 : Name.GetHashCode();
42:
43: //Get hash code for the ProductId field.
44: int hashCategory = Category.GetHashCode();
45:
46: //Get hash code for the ProductId field.
47: int hashMfgDate = MfgDate.GetHashCode();
48:
49: //Get hash code for the ProductId field.
50: int hashStatus = Status.GetHashCode();
51: //Calculate the hash code for the product.
52: return hashProductId ^ hashName ^ hashCategory & hashMfgDate & hashStatus;
53: }
54:
55: public static bool operator ==(Product a, Product b)
56: {
57: // Enable a == b for null references to return the right value
58: if (ReferenceEquals(a, b))
59: {
60: return true;
61: }
62: // If one is null and the other not. Remember a==null will lead to Stackoverflow!
63: if (ReferenceEquals(a, null))
64: {
65: return false;
66: }
67: return a.Equals((object)b);
68: }
69:
70: public static bool operator !=(Product a, Product b)
71: {
72: return !(a == b);
73: }
74: }