Fakultet
Fakultet

Reputation: 25

What is the List<T> Class?

I cannot understand this piece of code:

 public class BookCategory
 {
     public string CategoryName { get; set; }
     public List<Book> Books { get; set; }
 }
 public class Book
 {
     public string Title
     {
         get;
         set;
     }
 }

What does it mean List<Book>, and does it inherit from class Book or not ?

Upvotes: 1

Views: 261

Answers (6)

FishBasketGordo
FishBasketGordo

Reputation: 23142

List<Book>[MSDN] is a generic collection of Book objects. It doesn't inherit from Book. Rather, it contains zero or more Book objects in a collection.

Because the List<T> class is generic, it can be reused to provide list operations on a collection of any type of object. You can have List<int>, List<string>, List<object>, etc., but they all work from the same List<T> class, which is a great example of the DRY principle (Don't Repeat Yourself). In this example, T is called the type parameter and can be any .NET or user-defined type.

You can define you're own generic classes. Here's a trivial example of the syntax:

public class Foo<T>
{
    public T AnObject { get; set; }

    public Foo(T anObject)
    {
        AnObject = anObject;
    }
}

Some other very useful .NET generics are:

  • Stack<T>[MSDN]
  • Queue<T>[MSDN]
  • Nullable<T>[MSDN]
  • Dictionary<TKey,TValue>[MSDN]
  • and many more...

Generics are very useful and pervasive in .NET, so definitely familiarize yourself with this concept.

Upvotes: 9

Heinzi
Heinzi

Reputation: 172380

List<Book> is a list of books.

  • It's different than an ArrayList, since the list can only contain objects of type Book (or a subtype thereof).
  • It's different than an array of books (book[]), since a List data structure is dynamically sized and optimized for adding and removing items.

The notation List<Book> means: class List<T>, using Book as the generic type parameter T. For an introduction to generics (what they are, what problems they solve), I recommend the following article on MSDN:

To answer your second question: No, it does not inherit from Book. Think of it like a bookshelf: It can contain books, but it is not a book itself: The bookshelf does not have a title, nor does it have an author.

Upvotes: 3

Hugo Cantacuzene
Hugo Cantacuzene

Reputation: 85

in other terms

 List<Book> Books

will create a list of book objects named Books

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 613232

It's a generic container class whose elements have to be Book instances. The key word is generic and every C# text book will cover this concept.

Upvotes: 0

Joon
Joon

Reputation: 2147

This is called a Generic class and has been available since .NET 2.0

It contains a list of Book objects

Upvotes: 0

Femaref
Femaref

Reputation: 61467

It's a generic, a way of taking the type of an object into account to make strongly typed assumptions for an implementation.

Upvotes: 1

Related Questions