I am making a bookshelf application and I am having an issue trying to add data to my list. Here is the code that I am having trouble with:
static List<Book> book = new List<Book>();
public void AddBook()
{
int bookQuantity;
string bookTitle, bookAuthor;
bookQuantity = int.Parse(Console.ReadLine());
for(int x = 0; x <= bookQuantity; x++)
{
Console.WriteLine("Enter Title.");
bookTitle = Console.ReadLine();
Console.WriteLine("Enter Author.");
bookAuthor = Console.ReadLine();
Library.Add(bookTitle, bookAuthor);
}
}
When running, I get an error "No overload for method 'Add' takes 2 arguements." Any help/advice is welcome. Thank you in advance.
You want to add a Book
to your List<Book>
... but you're not actually creating a Book
instance. You probably want:
Book book = new Book(bookTitle, bookAuthor);
books.Add(book);
... that's after you've changed the name of your List<Book>
variable to books
, too. It should almost certainly be an instance variable, too. Additionally, I'd stop declaring variables at the start of your method - declare them where you need them. For example:
private readonly List<Book> books = new List<Book>();
public void AddBooks()
{
Console.WriteLine("How many books would you like to add?");
int count = int.Parse(Console.ReadLine());
// Note change from <= to <
for(int x = 0; x < count; x++)
{
Console.WriteLine("Enter Title.");
string title = Console.ReadLine();
Console.WriteLine("Enter Author.");
string author = Console.ReadLine();
books.Add(new Book(title, author));
}
}
You might also want to separate the "asking how many books to add" from the "adding a book" part:
private readonly List<Book> books = new List<Book>();
public void AddMultipleBooks()
{
Console.WriteLine("How many books would you like to add?");
int count = int.Parse(Console.ReadLine());
for(int x = 0; x < count; x++)
{
AddBook();
}
}
public void AddBook()
{
Console.WriteLine("Enter Title.");
string title = Console.ReadLine();
Console.WriteLine("Enter Author.");
string author = Console.ReadLine();
books.Add(new Book(title, author));
}
Then consider whether the user input should really be in this class, or possibly a class which calls this one. (Think about how difficult it is to unit test this code, for example.)
See more on this question at Stackoverflow