Created
September 18, 2018 21:31
-
-
Save mjs3339/a01ab49c8c1f5af5012994f5db47353b to your computer and use it in GitHub Desktop.
C# Access Performance of a Tuple and the Naming Convention of a KeyValuePair.
This file contains 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
[Serializable] | |
public class KvPair<T1, T2> : IStructuralEquatable, IStructuralComparable, IComparable | |
{ | |
public KvPair(T1 key, T2 value) | |
{ | |
Key = key; | |
Value = value; | |
} | |
public T1 Key {get;} | |
public T2 Value{get;} | |
int IComparable.CompareTo(object obj) | |
{ | |
return((IStructuralComparable) this).CompareTo(obj, Comparer<object>.Default); | |
} | |
int IStructuralComparable.CompareTo(object other, IComparer comparer) | |
{ | |
if(other == null)return 1; | |
if(!(other is KvPair<T1, T2> kvp))throw new ArgumentException("Object type is not of KVPair."); | |
var idx = comparer.Compare(Key, kvp.Key); | |
return idx != 0 ? idx : comparer.Compare(Value, kvp.Value); | |
} | |
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) | |
{ | |
if(other == null)return false; | |
if(!(other is KvPair<T1, T2> kvp) || !comparer.Equals(Key, kvp.Key))return false; | |
return comparer.Equals(Value, kvp.Value); | |
} | |
public int GetHashCode(IEqualityComparer comparer) | |
{ | |
return CombineHashCodes(comparer.GetHashCode(Key), comparer.GetHashCode(Value)); | |
} | |
public override int GetHashCode() | |
{ | |
return((IStructuralEquatable) this).GetHashCode(EqualityComparer<object>.Default); | |
} | |
private static int CombineHashCodes(int h1, int h2) | |
{ | |
return((h1 << 5) + h1) ^ h2; | |
} | |
public override bool Equals(object obj) | |
{ | |
return((IStructuralEquatable) this).Equals(obj, EqualityComparer<object>.Default); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment