Created
November 5, 2018 08:30
-
-
Save M-Zuber/dd95e16e25cf4624258af28eb40c81ec to your computer and use it in GitHub Desktop.
tuple equality
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
using System; | |
using System.Threading.Tasks; | |
namespace Example | |
{ | |
internal class Program | |
{ | |
private static void Main() | |
{ | |
var t1 = (f: new Foo { A = 1 }, b: new Bar { B = 2 }); | |
var t2 = (f: new Foo { A = 1 }, b: new Bar { B = 2 }); | |
Console.WriteLine(t1 == t2); | |
/** | |
* In Foo | |
* In Bar | |
* True | |
*/ | |
var t3 = (f: new Foo { A = 2 }, b: new Bar { B = 2 }); | |
var t4 = (f: new Foo { A = 1 }, b: new Bar { B = 2 }); | |
Console.WriteLine(t3 == t4); | |
/** | |
* In Foo | |
* False | |
*/ | |
// Why can't this case skip the check on Bar? | |
var t5 = (f: new Foo { A = 1 }, b: new Bar { B = 2 }); | |
var t6 = (f: new Foo { A = 1 }, b: new Bar { B = 2 }); | |
Console.WriteLine(t5 != t6); | |
/** | |
* In Foo | |
* In Bar | |
* False | |
*/ | |
var t7 = (f: new Foo { A = 2 }, b: new Bar { B = 2 }); | |
var t8 = (f: new Foo { A = 1 }, b: new Bar { B = 2 }); | |
Console.WriteLine(t7 != t8); | |
/** | |
* In Foo | |
* True | |
*/ | |
} | |
} | |
// Define other methods and classes here | |
class Foo | |
{ | |
public int A { get; set; } | |
public static bool operator == (Foo a, Foo b) | |
{ | |
return a?.Equals(b) == true; | |
} | |
public static bool operator !=(Foo a, Foo b) | |
{ | |
return !(a == b); | |
} | |
public override bool Equals(object obj) | |
{ | |
Console.WriteLine("In Foo"); | |
return obj is Foo f && f.A == A; | |
} | |
} | |
class Bar | |
{ | |
public int B { get; set; } | |
public override bool Equals(object obj) | |
{ | |
Console.WriteLine("In Bar"); | |
return obj is Bar b && b.B == B; | |
} | |
public static bool operator ==(Bar a, Bar b) | |
{ | |
return a?.Equals(b) == true; | |
} | |
public static bool operator !=(Bar a, Bar b) | |
{ | |
return !(a == b); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment