Kevin
Kevin

Reputation: 171

C# errors because of same name or just wrong syntax?

For an exercise, I have to create a library of sorts. The project specs indicate that there should be a class Book and Borrower with fields:

+---------------------------+            +--------------------------+
|Book                       |            |Borrower                  |
+---------------------------+            +--------------------------+ 
|private string title       |            |private string name       |
|private string author      |            |private Book b            |
|private int ISBN           |            

and these methods:

|public Book(string,string,int)|         |public Borrower(String)  |
|public string GetAuthor()     |         |public string GetName()  |
|public string GetTitle()      |         |public Book GetBook()    |
|public int GetISBN()          |         |public void SetBook(Book)|
|// add methods, if needed     |         |                         |
+------------------------------+         +-------------------------+

So I code this into my compiler but in my Borrower class I have errors like:

class Borrower
{
    private string name;
    private Book b;

    public Borrower(string n)
    {
        name = n;
    }

    public string GetName()
    {
        return name;
    }

    public Book GetBook()
    {
        return b;
    }

    public void SetBook(Book) //I get an error here (Identifier expected)
    {
        Book = b; // error here says Book is type but is used as a variable
    }
}

This is my Book class there are no errors here

class Book
{
    private string title, author;
    private int ISBN;

    public Book(string a, string b, int c)
    {
        title = a;
        author = b;
        ISBN = c;
    }

    public string GetAuthor()
    {
        return author;
    }

    public string GetTitle()
    {
        return title;
    }

    public int GetISBN()
    {
        return ISBN;
    }
}

Do I get the errors because I have a method Book which is the same as the name of the class or can I actually use the class as a method?

Upvotes: 2

Views: 60

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

This method

public void SetBook(Book)
{
    Book = b;
}

should be rewritten as follows:

public void SetBook(Book b)
{
    this.b = b;
}

Otherwise the object passed as parameter would have no name. I used the same name as your field Book b, so I added this.b for disambiguation.

Upvotes: 5

Related Questions