I have the following class with the 2 equal methods as documented by MSDN.
public class Book
{
public string bookTitle {get; private set;}
public IReadOnlyCollection<Author> authors {get; private set;}
public string ISBN {get; private set;}
public int numberofpages {get; private set; }
public string Genre {get; private set; }
public Book(string bookTitle, IReadOnlyCollection<Author> authors, string ISBN, int numberofpages, string genre)
{
if(string.IsNullOrWhiteSpace(bookTitle)){
throw new ArgumentNullException("Book Must Have Title!");
}
this.bookTitle = bookTitle;
if(authors.Count < 0){
throw new ArgumentNullException("You must provide at least one author!");
}
this.authors = new ReadOnlyCollection<Author>(new List<Author>(authors));
if(String.IsNullOrWhiteSpace(ISBN)){
throw new ArgumentNullException("A Book Has to have an ISBN number. Check online or the back cover");
}
this.ISBN = ISBN;
if(numberofpages <= 0){
throw new ArgumentNullException("A Book has more than one page!");
}
this.numberofpages = numberofpages;
if(String.IsNullOrWhiteSpace(genre)){
throw new ArgumentNullException("A Book has a genre. Find it and input it");
}
this.Genre = genre;
}
public override bool Equals(Object obj)
{
if (obj == null)
{
return false;
}
Book p = obj as Book;
if ((System.Object)p == null)
{
return false;
}
return (bookTitle == p.bookTitle) && (authors == p.authors) && (numberofpages == p.numberofpages) && (ISBN == p.ISBN) && (Genre == p.Genre);
}
public bool Equals(Book p)
{
if ((object)p == null)
{
return false;
}
return (bookTitle == p.bookTitle) && (authors == p.authors) && (numberofpages == p.numberofpages) && (ISBN == p.ISBN) && (Genre == p.Genre);
}
public class Author
{
public int ID {get; private set;}
public string firstname {get; private set;}
public string lastname {get; private set;}
public(int id, string firstname, string lastname)
{
this.ID = id;
this.firstname = firstname;
this.lastname = lastname;
}
//Rest of code here: just toString method
}
My Problem:
Both these methods will evaluate to false because I'm creating a new List before I assign my authors in the constructor:
this.authors = new ReadOnlyCollection<Author>(new List<Author>(authors));
I did this so that a user cannot make changes to the ReadOnlyCollection
outside of the class. Any changes made would be on a copy of the collection. With that in mind, how do I get my Equals to method to work properly, given that I create a new list?