Created
May 12, 2016 12:40
-
-
Save arlm/116ba07b86626a4d115c3eceb1a139e2 to your computer and use it in GitHub Desktop.
GetHashCode, IEquatable and IComparable Support
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// IEquatable<T>, IComparable, IComparable<T> | |
#region GetHashCode, IEquatable and IComparable Support | |
public override int GetHashCode() | |
{ | |
return T?.Id ?? 0 ^ T.Value1 ^ T.Value2; | |
} | |
public static bool operator ==(T left, T right) | |
{ | |
if (ReferenceEquals(left, null)) | |
{ | |
return ReferenceEquals(right, null); | |
} | |
return left.Equals(right); | |
} | |
public static bool operator !=(T left, T right) | |
{ | |
return !(left == right); | |
} | |
public static bool operator <(T left, T right) | |
{ | |
return (Compare(left, right) < 0); | |
} | |
public static bool operator >(T left, T right) | |
{ | |
return (Compare(left, right) > 0); | |
} | |
public static bool operator <=(T left, T right) | |
{ | |
return (Compare(left, right) <= 0); | |
} | |
public static bool operator >=(T left, T right) | |
{ | |
return (Compare(left, right) >= 0); | |
} | |
public override bool Equals(object obj) | |
{ | |
var other = obj as T; | |
if (ReferenceEquals(other, null)) | |
{ | |
return false; | |
} | |
return CompareTo(other) == 0; | |
} | |
public bool Equals(T other) | |
{ | |
if (ReferenceEquals(other, null)) | |
{ | |
return false; | |
} | |
return CompareTo(other) == 0; | |
} | |
public int CompareTo(object other) | |
{ | |
if (other == null) | |
return 1; | |
var session = other as T; | |
if (session == null) | |
throw new ArgumentException("A T object is required for comparison.", nameof(other)); | |
if (this == session) | |
return 0; | |
return CompareTo(session); | |
} | |
public int CompareTo(T other) | |
{ | |
if (ReferenceEquals(other, this)) | |
{ | |
return 0; | |
} | |
if (ReferenceEquals(other, null)) | |
{ | |
return 1; | |
} | |
return GetHashCode().CompareTo(other.GetHashCode()); | |
} | |
public static int Compare(T left, T right) | |
{ | |
if (ReferenceEquals(left, right)) | |
{ | |
return 0; | |
} | |
if (ReferenceEquals(left, null)) | |
{ | |
return -1; | |
} | |
if (ReferenceEquals(right, null)) | |
{ | |
return 1; | |
} | |
return left.CompareTo(right); | |
} | |
public override string ToString() | |
{ | |
return string.Format("{0} ID: {1}", GetType().Name, T?.Id); | |
} | |
#endregion |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment