Created
January 30, 2018 15:25
-
-
Save BillWagner/30d6383a16d708acc0d34bd4940ddbda to your computer and use it in GitHub Desktop.
Equality and Symmetry
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
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