In C# 4.0 (or earlier if it can be done), how does a parent class pass a reference of itself to a child class. For example:
class Book
{
public string bookname = "a";
public static List<Page> pages = new List<Page>();
static void Main(string[] args)
{
Page pageone = new Page("one");
pages.Add(new Page("one"));
}
}
public class Page
{
Book book;
public Page(string pagetitle)
{
Console.WriteLine(pagetitle);
Console.WriteLine("I'm from bookname :?");
}
}
How can I get Page to recognize which book it's in? I'm trying to pass the Book class in the constructor, but don't know how.
You're having trouble because you've made your book class the entry point for your application, which means you don't have an actual Book instance.
Try something like this instead:
public class Program
{
static void Main(string[] args)
{
Book book1 = new Book();
book1.AddPage("one");
}
}
public class Book
{
public string Bookname = "a";
public List<Page> Pages = new List<Page>();
public void AddPage(string pageTitle)
{
Pages.Add(new Page(this, pageTitle));
}
}
public class Page
{
Book book;
public Page(Book b, string pagetitle)
{
book = b;
Console.WriteLine(pagetitle);
Console.WriteLine("I'm from book '{0}'.", book.Bookname);
}
}