I have a Use Case where I want to validate a specific property in a list of objects to make sure it is unique. The basic setting can be seen in the code below.
class Program
{
static void Main(string[] args)
{
Directory myDirectory = new Directory("Interaction Design");
myDirectory.Books.Add(new Book("978-0-262-64037-4", "The Design of Everyday Things")); //Should be added
myDirectory.Books.Add(new Book("978-0-262-13474-3", "Designing Interactions")); //Should be added
myDirectory.Books.Add(new Book("978-0-262-13474-3", "Whoops, I slipped up")); //Should NOT be added
}
}
public class Directory
{
public Directory(string name)
{
Name = name;
}
public string Name { get; set; }
public List<Book> Books { get; set; } = new List<Book>();
}
public class Book
{
public Book(string isbn, string title)
{
Isbn = isbn;
Title = title;
}
public string Title { get; set; }
public string Isbn { get; set; }
}
Now, in the code above, adding a new Book in the List of Books should throw an exception if the ISBN
number isn't unique.
I would like to extend on the .Add()
method of the List and add that validation, but I'm not sure how to actually do that.
I've seen similar things, but they all assume that the Directory inherits from List and you write an overriding .Add method to the Directory - which doesn't look like a valid solution in this case.
Perhaps my general approach is backwards?
Please advice.