user2783193
user2783193

Reputation: 1012

proper way of implementing CompareTo method

I'm trying to understand proper implementation and usage of CompareTo method.

Let's say that I have Book object and somewhere in code I want to compare newly created book object with one from the database.

Book newBook = new Book();
Book dbBook = repository.GetBook(1);

so basically I'm trying to compare two objects with multiple parametars

roughly I have following bellow, so how would you implement this method having those 3 requirements?

public int CompareTo(object obj)
{
    if(obj is Book)
    {
      Book b = (book)obj;
      var b = Name.ToUpper().CompareTo(b.Name.ToUpper());
    }
    else
    { throw new Exception("Not a book instance"); }

}

Upvotes: 1

Views: 1941

Answers (1)

Roy Dictus
Roy Dictus

Reputation: 33139

First of all, it's better to use generics, to to define your Book class as:

public class Book : IComparable<Book>

and then to implement the CompareTo method:

public int CompareTo(Book book)
{
    int result = Title.CompareTo(book.Title);
    if (result == 0)
    {
       result = Edition.CompareTo(book.Edition);
       if (result == 0)
       {
            result = Language.CompareTo(book.Language);
       }
    }

    return result;
}

This of course assumes that the properties Title, Edition and Language are of types that implement IComparable (such as string).

Upvotes: 4

Related Questions