Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 824
tonysepia Avatar asked Sep 21 '13 20:09

tonysepia


2 Answers

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.

like image 62
MarcinJuraszek Avatar answered Sep 21 '22 18:09

MarcinJuraszek


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;
like image 30
Douglas Avatar answered Sep 17 '22 18:09

Douglas