Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a List<Book> c# console application

Tags:

c#

I want to create a List that holds a couple of books with the book title, authors name and year of publication. example: ( AuthorLastName, AuthorFirstName, “The book title”, year.)

I know how to create List<int>, for example:

class Program
{
    static void Main()
    {
    List<int> list = new List<int>();
    list.Add(10);
    list.Add(20);
    list.Add(25);
    list.Add(99);
    }
}

But the problem is, if I want to create a list of books, I can't simply make a list<string> or list<int> because I want it to contain strings and int's (as the example above).

So, Can anyone explain how I can make a List of books?

like image 247
user2057693 Avatar asked Dec 05 '25 06:12

user2057693


1 Answers

You need to create a class called Book that contains the properties you want to have. Then you can instantiate a List<Book>.

Example:

public class Book
{
   public string AuthorFirstName { get; set; }
   public string AuthorLastName { get; set; }
   public string Title { get; set; }
   public int Year { get; set; }
}

And then, to use it:

var myBookList = new List<Book>();
myBookList.Add(new Book { 
                         AuthorFirstName = "Some", 
                         AuthorLastName = "Guy", 
                         Title = "Read My Book", 
                         Year = 2013 
                        });
like image 143
Mark Avenius Avatar answered Dec 06 '25 22:12

Mark Avenius