Suppose I have the following class:
public class Author
{
public int ID {get; private set;}
public string firstName {get; private set;}
public string lastName {get; private set; }
public Author(int id, string firstname, string lastname)
{
this.ID = ID;
this.firstName = firstname;
this.lastName = lastName;
}
public static Author Clone(Author clone)
{
Author copyAuth = new Author(clone.ID, clone.firstName, clone.lastName);
return copyAuth;
}
}
and
public class Book
{
public string bookTitle {get; private set;}
private List<Author> authors;
private List<Author> copyofAuthors;
public string ISBN {get; private set; }
public Book(string bookTitle, List<Author> authors, string ISBN)
{
copyofAuthors = new List<Author>();
this.bookTitle = bookTitle;
this.ISBN = ISBN;
//How do I create a deep copy of my authors List?
foreach(Author copy in authors)
{
Author addAuthors = Author.Clone(copy);
copyofAuthors.Add(addAuthors);
}
}
}
How would I create a deep copy of my List<Authors>
collection? I've read other pages on StackOverFlow that suggest serialization, and suggestions that I'm unfamiliar with and seem confusing.
I followed this link to create my clone method.
Questions 1:
Is the above implementation considered a deep copy? If so, is it okay to do it this way? By that I mean, a foreach loop in the constructor copying the authors to a new list collection.
Question 2:
If I modify anything in the copyofAuthor collection, it no longer references the original collection correct? So the original collection should remain the same?
Update #1 :
public List<Author> Authors
{
get
{
return returnAuthors(authors);
}
}
private List<Author> returnAuthors(List<Author> copyList)
{
List<Author> getAuthors = new List<Author>();
foreach(Author copy in copyList){
getAuthors.Add(Author.Clone(copy));
}
return getAuthors;
}
Have I implemented my getter collection properly such that when it returns the List collection, it's independent of the original collection? So any changes made from the collection returned from the getter will not be reflected in the original collection correct?
Update #2:
With ReadOnlyCollection
public class Book
{
public string bookTitle {get; private set;}
private ReadOnlyCollection<Author> authors;
public string ISBN {get; private set; }
public Book(string bookTitle, ReadOnlyCollection<Author> authors, string ISBN)
{
this.bookTitle = bookTitle;
this.ISBN = ISBN;
//Is it okay to do this?
this.authors = authors;
}
public List<Author> Authors
{
get
{ //Create a shallow copy
return new ReadOnlyCollection<Author>(authors);
}
}
}