Djordje Gligorijevic
Djordje Gligorijevic

Reputation: 27

How to access property of a subclass

I have 1 abstract class 'Book' and 2 subclasses 'Comic' and 'Novel' extended from first abstract class. In the main method I have to create array of books that will store instances of comics and novels.

My problem is that I don't know how to access a variable price of class 'Comic'. I have getters in 'Comic' class but i can access only the variables which are part of parent class 'Book'.

abstract class Book
{
    private string title;
    private string author;
    ...
}

class Comic : Book
{
    private double price;
    ...
}



static void Main(string[] args) {
   ...
   for (int i = 0; i < books.Length; i++) {
        if (books[i] is Comic)
           Console.WriteLine("Price of comic is..."); 
           // Here i want to access books[i].price or books[i].Price with getter.
   }

   ...
}

Upvotes: 0

Views: 656

Answers (2)

SharpNip
SharpNip

Reputation: 360

Private variables (as shown in your Book class) are not accessible outside of the scope of the class. This means that, for example, book.title will display an error.

To make your "price" property available, I would first recommend bringing that variable to the Book class instead (as it can be assumed that all books or derived classes should have a price). After which you can create an public property as follows:

public double Price { get; set; }

This will expose the Price property when attempting to access objects within your books collection.

As to access your price in your main method, something like the following would probably suit:

static void Main(string[] args) {
...
    for (int i = 0; i < books.Length; i++) {
        if (books[i] is Comic)
           Comic c = books[i] as Comic;
           Console.WriteLine("Price of comic is..." + c.Price); 
    }
...
}

Quickly, accessors in C# tend to follow the same sort of rules as with a lot of languages with similar syntax (such as Java or C++):

Public : can be accessed at any level of scope that utilizes an instance of that class.

Private : can be accessed only within the scope of the class, and cannot be directly accessed outside of it.

Upvotes: 0

Gustavo Santos
Gustavo Santos

Reputation: 125

First, you need to change the accessibility of the price field, or create a public property, then, you can use the Pattern Matching feature (check it on the 'if' line, I wrote a c after the Comic type, that cast the Book to a Comic if the 'is' check is true, and you can use that variable inside the 'if' statement):

static void Main(string[] args) {
...
    for (int i = 0; i < books.Length; i++) {
        if (books[i] is Comic c)
           Console.WriteLine("Price of comic is..." + c.price); 
           // Here i want to access books[i].price or books[i].Price with getter.
    }
...
}

Upvotes: 1

Related Questions