var books = new List<Book>(3);
foreach (Book item in books)
{
item.Title = Console.ReadLine();
item.Countofpage = int.Parse(Console.ReadLine());
}
When I enter the title into the console, my program just closes.
Please help
CodePudding user response:
You are initializing the list with the constructor that sets the capacity of the list. But this will not do what you expect. A list uses an array as collection which will be re-created with the double-size if the item count exceeds the capacity. So this constructor can be used to optimize it, because the array can be correctly sized at the beginning.
But the list is still empty no matter what capacity you use.
So you can use a for-loop
:
int capacity = 3;
var books = new List<Book>( capacity );
for(int i = 0; i < capacity; i )
{
Book book = new Book();
book.Title = Console.ReadLine();
book.Countofpage = int.Parse(Console.ReadLine()); // use int.TryParse
books.Add(book);
}
Side-note: don't confuse it with a array, where you really get the size:
Book[] books = new Book[capacity]; // contains 3 books which are all null
CodePudding user response:
If you want to create list and fill items of it. You can look through blow example. Before that I want to mention a few points. In C#, capacity of List is defined explicitly, of course you can set capacity but it's not mandatory.
var books = new List<Book>();
var booksCount = 0;
Console.WriteLine("Enter book's count:");
booksCount = int.Parse(Console.ReadLine());
for (int i = 0; i < booksCount; i )
{
books.Add(
new Book()
{
Title = Console.ReadLine(),
Countofpage = int.Parse(Console.ReadLine())
});
}
foreach (var book in books)
{
Console.WriteLine($"Book title: {book.Title}, page count:{book.Countofpage}");
}