Home Overriding the .Add method in a List of... with validation
Reply: 0

Overriding the .Add method in a List of... with validation

user1596
1#
user1596 Published in April 22, 2018, 12:56 am

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.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.317736 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO