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!
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With