Skip to content

Instantly share code, notes, and snippets.

@BillWagner
Created January 30, 2018 15:25
Show Gist options
  • Save BillWagner/30d6383a16d708acc0d34bd4940ddbda to your computer and use it in GitHub Desktop.
Save BillWagner/30d6383a16d708acc0d34bd4940ddbda to your computer and use it in GitHub Desktop.
Equality and Symmetry
using System;
namespace symmetry
{
public class Person : IEquatable<Person>
{
public string FirstName {get;set;}
public string LastName {get;set;}
public bool Equals(Person other)
{
// Guard against 'other' being a type derived from Person:
if (other.GetType() != typeof(Person))
return false;
return this.FirstName == other?.FirstName && this.LastName == other?.LastName;
}
}
public class Student : Person, IEquatable<Student>
{
public int Level {get;set;}
public bool Equals(Student other)
{
// Guard against 'other' being a type derived from Student
if (other.GetType() != typeof(Student))
return false;
return base.Equals(other) && this.Level == other?.Level;
}
}
class Program
{
static void Main(string[] args)
{
Person p = new Person
{
FirstName = "Bill",
LastName = "Wagner"
};
Student s = new Student
{
FirstName = "Bill",
LastName = "Wagner",
Level = 17
};
Console.WriteLine(p.Equals(s));
Console.WriteLine(s.Equals(p));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment