3

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.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Eugene
  • 10,957
  • 20
  • 69
  • 97
  • C# and most object-oriented languages I know have no concept of parent class and child class. Not surprisingly, there's no built-in mechanism to pass a reference to the parent instance down to the child instance. – John Saunders Oct 08 '11 at 01:04
  • @JohnSaunders Actually Java inner classes model exactly that kind of relation. Though you can easily fix it in C# - just a bit syntax sugar after all. – Voo Oct 08 '11 at 01:07
  • @Voo, that's where I was coming from...but C# has nested classes as opposed to inner classes. see http://blogs.msdn.com/b/oldnewthing/archive/2006/08/01/685248.aspx – Eugene Oct 08 '11 at 01:17
  • 1
    @user389823 Yeah I know, otherwise I wouldn't have stated you have to implement it yourself in C#, would I? ;) But I wanted to point out at least one quite popular object oriented language that allows to model this easily. – Voo Oct 08 '11 at 01:20
  • @John Saunders "Most" is debatable (even if this is the case with C#) ;-) –  Oct 08 '11 at 01:31

2 Answers2

7

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);
    }
}
Paul Batum
  • 8,165
  • 5
  • 40
  • 45
4

Just add a field for Book in the Page class

Then create an overload that takes a Book argument.

Use this to reference the Book object when calling the constructor from the Book class

private Book _book;
public Page(Book book, string pagetitle);
{
   this._book = book
}

// Usage in the Book class
Page pageone = new Page(this, "one");
Gabe
  • 49,577
  • 28
  • 142
  • 181