You can't create instances of static classes:
Book myBook = new Book();
-> Remove the
static
modifier from your three "book-classes".
Variables declared in methods can't have modifiers because they're automatically and always only visible within that method:
public string input;
The advice
would be to remove the
public
modifier from that variable declaration, but: You then re-declare
input
here:
string input = Console.ReadLine();
-> Completely remove the first declaration of
input
.
TextBook.Grade
is of type
char
, so you can't assign a
string
:
myText.Grade = Convert.ToString(Console.ReadLine());
-> Proposed solution:
string gradeInput = Console.ReadLine();
if (gradeInput.Length == 1)
{
myText.Grade = gradeInput[0];
}
else
{
}
With these modifications all compiler errors should be dealt with.
Then there are some other issues which can be considered style/good practice issues:
- Don't validate values in property-setters. Alternatives: Either provide all values through the constructor, validate them there and in case of an invalid value, throw an exception. Or have a dedicated method for validation like:
bool IsValid()
{
}
(Which would, in an application where those books would subsequently be stored into a database, be called before the book would be stored and in case it's invalid, the saving-process would be stopped. So, in your case it would be a bit artificial.)
-
Console.ReadLine()
already returns a
string
. So passing it into
Convert.ToString(..)
is completely redundant:
Convert.ToString(Console.ReadLine());
- For converting strings into other types, the preferred (static) methods are
.Parse(..)
or
.TryParse(..)
of the according types. The difference being that .Parse(..) returns the parsed value if successful and throws an exception if not successful while .TryParse(..) returns
true
if successful and places the parsed value into an
out
-parameter and returns
false
if not successful. The latter is often the more convenient option:
double price;
if (!Double.TryParse(Console.ReadLine(), out price))
{
}
A free PDF-book on programming in C#:
Introduction to Programming with C# / Java Books[
^]