Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

I am a newbie attempting to learn OOP with C#. I have 2 classes - base class = LibraryAsset and derived class = Book. The private fields for the 2 classes are below.

 

Library Asset: _title, _checkedOut

Book: _isbn, _author

 

I have written the necessary properties and methods.

 

The following code runs when the program starts

 

Book myBook = new Book();

myBook.Author = "John Doe";

myBook.CheckedOut = false;

myBook.ISBN = "554666";

myBook.Title = "Learning OOP";

myBook.CheckOut();

Console.WriteLine(myBook);

 

I have an ToString override method in the Book class and the LibraryAsset to return the associated fields. See below:

 

 

public override string ToString() // from Book Class

{

return String.Format( "Author: {0} \nISBN: {1}",

_author,_isbn);

}

 

public override string ToString() // from LibraryAsset class

{

return String.Format("Title: {0} \nChecked Out: {1}",

_title,_checkedOut);

}

 

My question is how do I write out all of the myBook properties to the screen. Console.WriteLine(myBook) only writes out the _author and _isbn. What do I need to do to write out the _title and _checkedOut?

 

Thanks for your help!

  • Leaders
Posted

Firstly, I recommend using the CS tags to make easier reading. Secondly, you could do either of the following:

[CS]

// If _title and _checkedOut are public or protected...

public override string ToString() // from Book Class

{

return String.Format( "Author: {0} \nISBN: {1}\n Title: {3}\nChecked Out? {4}",

new Object[] {_author, _isbn, _title, _Checked Out});

}

[/CS]

[CS]

public override string ToString() // from Book Class

{

// Use the base keyword to access overridden/shadowed base members

return base.ToString() + String.Format( "Author: {0} \nISBN: {1}",

_author,_isbn);

}

[/CS]

[sIGPIC]e[/sIGPIC]

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...