Search code examples
c#icomparable

Having problems making an Comparable class


This is my first post here. I'm having problems with trying to make an comparable class, and i was hoping you could help me out.

The error:

Error 1 'OutputMasterLibrary.Student' does not implement interface member 'System.Collections.Generic.IComparer.Compare(OutputMasterLibrary.Student, OutputMasterLibrary.Student)''

My code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace OutputMasterLibrary 
{
    public class Student : IComparable, IComparable<Student>
    {
        string name { get; set; }
        int age { get; set; }
        int studentNumber { get; set; }


        public Student(string myName, int myAge, int myNumber)
        {
            name = myName;
            age = myAge;
            studentNumber = myNumber;
        }


        public override bool Equals(object obj)
        {
            Student other = obj as Student;
            if (other == null)
            {
                return false;
            }
            return (this.name == other.name) && (this.studentNumber == other.studentNumber) && (this.age == other.age);
        }


        public override int GetHashCode()
        {
            return name.GetHashCode() + studentNumber.GetHashCode() + age.GetHashCode();
        }
    }
}

Solution

  • You have implemented both IComparable and Icomparable<T>. So you have to implement both CompareTo methods.

        public int CompareTo(object obj) // implement method from IComaparable<T> interface
        {
            return CompareStudent(this, (Student)obj);
        }
    
        public int CompareTo(Student obj) // implement method from IComaparable interface
        {
            if (obj != null && !(obj is Student))
                throw new ArgumentException("Object must be of type Student.");
            return CompareStudent(this, obj);
        }
    
        public int CompareStudent(Student st1, Student st2)
        {
            // You can change it as you want
            // I am comparing their ages 
            return st1.age.CompareTo(st2.age);
        }