tonysepia
tonysepia

Reputation: 3500

C# Can't access base properties of a class (only inherited)

Here is my code (should be easy to understand what I'm trying to achieve):

public class Order
{
    private Drink drink;
    public Drink Drink {get { return drink; } set { drink = value; }}
}

public class Drink
{
    enum colour 
    {
        Red, Transparent
    };
}

public class cocktail : Drink
{
    private int alcoholContent;
    public int AlcoholContent  { get { return alcoholContent; } set { alcoholContent = value; } }
}

And then I'm trying to access the properties, but they aren't there:

Order order = new Order();
order.Drink = new cocktail();
order.Drink. <- no alcohol content?

Why is that? I thought I did create a cocktail class, not just a Drink? What am I doing wrong?

Thank you!

Upvotes: 7

Views: 8766

Answers (4)

Thilina H
Thilina H

Reputation: 5804

If you want to get concrete class properties then should have to explicitly cast to concrete type.

(order.Drink as Cocktail).AlcoholC ontent <- works just fine

Or

You can keep a virtual property as Alcoholicontent in Drink class and override it in cocktail class. Then you can access those properties.

Upvotes: 1

Tony
Tony

Reputation: 17637

You can cast it. Try:

Order order = new Order();
order.Drink = new cocktail();
(order.Drink as cocktail).AlcoholContent = 0 ; // please dont drink

Upvotes: 1

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

You can't use AlcoholContent property directly, because you're using Coctail instance through Drink reference.

Order order = new Order();
order.Drink = new cocktail();
//  order.Drink. <- no alcohol content?
((Coctail)order.Drink).AlcoholContent <- works just fine

You have to use explicit (Coctail) cast to use members specific to Coctail class.

Why is that? Consider a situation, where there is another class named SoftDrink:

public class SoftDrink : Drink
{
}

You'd still be able to assign SoftDrink instance to order.Drink:

Order order = new Order();
order.Drink = new SoftDrink();
//  order.Drink. <- no alcohol content? It's a SoftDring!!

And because order.Drink property can handle every Drink, you can only use members specified for Drink class. Even if there is really a more specific class instance assigned to that property.

Upvotes: 9

Douglas
Douglas

Reputation: 54877

You need to distinguish between the actual type and the declared type. In your case, although you instantiate a cocktail, you are referencing it as a Drink, which does not expose any properties.

To access the properties defined in the cocktail class, you need to type-cast your reference:

((cocktail)order.Drink).AlcoholContent = 4;

Upvotes: 2

Related Questions