Created
August 2, 2019 13:57
-
-
Save daneb/10751c5c0d0cb22d1e0168c71c41fc92 to your computer and use it in GitHub Desktop.
Type Constraint
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
public sealed class MyTuple<T1, T2> : IEquatable<MyTuple<T1, T2>> | |
{ | |
// Create Instance for Comparing Against Self. | |
// If we used type against Interface we can compare two values | |
private static readonly IEqualityComparer<T1> FirstComparer = EqualityComparer<T1>.Default; | |
private static readonly IEqualityComparer<T2> SecondComparer = EqualityComparer<T2>.Default; | |
private readonly T1 _first; | |
private readonly T2 _second; | |
public MyTuple(T1 first, T2 second) | |
{ | |
this._first = first; | |
this._second = second; | |
} | |
public T1 First { get { return _first; } } | |
public T2 Second { get { return _second; } } | |
public bool Equals(MyTuple<T1, T2> myTuple) | |
{ | |
if (myTuple != null && | |
FirstComparer.Equals(_first, myTuple.First) && | |
SecondComparer.Equals(_second, myTuple.Second)) | |
return true; | |
return false; | |
} | |
// We need to override the base class implementations as per Microsoft Docs | |
// https://docs.microsoft.com/en-us/dotnet/api/system.iequatable-1.equals?view=netframework-4.8#System_IEquatable_1_Equals__0_ | |
// Equals is always coupled with GetHashCode() | |
public override bool Equals(Object someTuple) | |
{ | |
MyTuple<T1, T2> theirTuple = someTuple as MyTuple<T1, T2>; | |
return this.Equals(theirTuple); | |
} | |
public override int GetHashCode() | |
{ | |
return FirstComparer.GetHashCode(_first) + SecondComparer.GetHashCode(_second); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment