Skip to content

Instantly share code, notes, and snippets.

@M-Zuber
Created November 5, 2018 08:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save M-Zuber/dd95e16e25cf4624258af28eb40c81ec to your computer and use it in GitHub Desktop.
Save M-Zuber/dd95e16e25cf4624258af28eb40c81ec to your computer and use it in GitHub Desktop.
tuple equality
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