I am so confused on this. I need to write an indexer returning bool that will search for the book collection for a specific title and return true if the title is in the collection; otherwise return false, and I have to use the foreach statement to loop/iterate thru the collection and ingnore any books that have a null reference, and test this functionality in the Main routine. Here are my files (this is all in C#). Sorry I am so blonde......
Code:Book.cs using System; namespace Book { public class Book { private string title ; public string Title { get { return title ; } set { title = value ; } } public Book() { title = "Unknown title" ; } } } BookMain.cs using System; namespace Book { public class BookMain { public BookMain() { } public static void Main (string [] args) { Book myBooks = new Book() ; Console.WriteLine ("Created " + myBooks) ; // Create several books Book [] manyBooks = new Book [5]; // Create the individual books. It is an error not to // create each reference in the array. for (int i = 0; i < manyBooks.Length; i++) { manyBooks [i] = new Book() ; } manyBooks[0].Title = "Tom Sawyer" ; manyBooks[1].Title = "Going to Town" ; manyBooks[2].Title = "Intro to C#" ; // list the books for (int i = 0; i < manyBooks.Length; i++) { Console.WriteLine ("Book {0} title: {1}", i + 1, manyBooks [i].Title) ; } Console.Write ("\n\n") ; BookColl moreBooksColl = new BookColl (10); moreBooksColl [0] = "The best book"; moreBooksColl [3] = "Science Fiction"; moreBooksColl.display ("More Books Collection"); } } } BookColl.cs sing System; namespace Book { public class BookColl { private Book [] books ; public BookColl() { } public string this [int index] { // Make sure the index is within range get { CheckNull (index); if (index >= books.Length || index < 0) { return "Unknown book number" ; } return books[index].Title ; } set { CheckNull (index); if (index >= books.Length || index < 0) { return ; // out of range, can't set } books [index].Title = value ; } } public BookColl (int size) { books = new Book [size]; } private void CheckNull (int index) { if (books [index] == null) { books [index] = new Book(); } } public void display (string title) { Console.WriteLine ("\n========= {0} ========\n\n", title); foreach (Book bk in books) { if (bk == null) { continue; } Console.WriteLine("title {0} active", bk.Title); } Console.WriteLine ("\n========= End {0} ========\n\n", title); } } }



LinkBack URL
About LinkBacks
......


