Overriding Object .Equals Method

Hey, I'm working on an assignment and need some help. I have a class called Patient and an Array of that Patient object shown below. I'm supposed to prompt a user to enter an ID and check if that ID already exists in the Array by using an overridden .Equals method. Following what's in my book, I put together some code but I'm confused how this is supposed to work. Can anyone explain how to use the .Equals method to check if an item already exists? Thanks in advance!

 public static void Main(string[] args) { Patient[] patientArray = new Patient[5]; Patient patient = new Patient(); for(int i = 0; i < patientArray.Length; i++) { patientArray[i] = new Patient(); Console.Write("Please enter a patient number: "); //This is where I'm stuck--------------------------------------- patientArray[i].patientNum = Convert.ToInt16(Console.ReadLine()); if (patient.Equals(patientArray[i])) { Console.Write("Patient number already exists"); } } } public class Patient : IComparable { private int _patientNum; private string _patientName; private int _patientAge; private double _amountDue; public int patientNum { get { return this._patientNum; } set { this._patientNum = value; } } public string patientName { get { return this._patientName; } set { this._patientName = value; } } public int patientAge { get { return this._patientAge; } set { this._patientAge = value; } } public double amountDue { get { return this._amountDue; } set { this._amountDue = value; } } public Patient() { this._patientNum = 9; this._patientName = "ZZZ"; this._patientAge = 0; this._amountDue = 0; } public override bool Equals(Object o) { bool isEqual; if(this.GetType() != o.GetType()) { isEqual = false; } else { Patient temp = (Patient)o; if(this.patientNum == temp.patientNum) { isEqual = true; } else { isEqual = false; } } return isEqual; } public override int GetHashCode() { return this.patientNum.GetHashCode(); } } 

by Gummoasshit via /r/csharp

Leave a Reply