Reputation: 6557
I have a question about polymorphism. Here are 3 simple classes:
public class Book
{
public string Name;
}
public class Encyclopedia : Book
{
public int Volume;
}
public class Library
{
public Book[] Books;
}
The Library class i instantiated like this:
private void btnMakeLibrary_Click(object sender, EventArgs e)
{
Book[] books = new Book[3];
books[0] = new Book();
books[0].Name = "Book Name 1";
books[1] = new Book();
books[1].Name = "Book Name 2";
books[2] = new Encyclopedia();
books[2].Name = "Encyclopedia 1";
((Encyclopedia)books[2]).Volume = 10;
Library library = new Library();
library.Books = books;
}
The array consisting of Book types are populated by an Encyclopedia type. Why is this possible? I could understand if it was the other way around where an array of the Encyclopedia type was populated by one of its base classes. Maybe I am confusing it with an earlier question about casting between base classes and child classes.
Upvotes: 2
Views: 2460
Reputation: 33
A base class can always contain a reference to its children because a child class always contains the base part. That's the reason you can assign any derived classes of Book into Library which is a collection of Books.
An Encyclopedia is a Book - this statement holds true always. I hope this clears your confusion.
Upvotes: 1
Reputation: 14350
I'm not sure which part you're confused about:
The array must be an array of books. An encyclopedia is a type of book. Therefore an array of books can include any type of book, including encyclopedias. Contrarily, an array of encyclopedias cannot include any old book, because we expect them all to be encyclopedias with volume properties.
The third book is an encyclopedia, and you cast to it. You can see this on the line that says ((Encyclopedia)books[2]).Volume = 10;
. This is casting, which is allowed, though not necessarily encouraged because the operation can fail at runtime. Imagine if you had written this: ((Encyclopedia)books[1]).Volume = 10;
. That would compile but fail at runtime.
Upvotes: 4