Say I have an object, someDrink
. It could be of type CocaCola
or Pepsi
which both inherit the abstract Cola
(which inherits Drink
) or any kind of drink for that matter. I have a method that returns a string of the most preferred beverage.
public string PreferredDrink(Drink someDrink)
{
var orderOfPreference = new List<Type> {
typeof (Cola),
typeof (PurpleDrank),
typeof (LemonLimeBitters)
...
}
foreach (drinkType in orderOfPreference) {
if (someDrink.GetType() == drinkType) {
return someDrink.ToString()
}
}
throw new Exception("Water will be fine thank you");
}
The code above will not work, because the type of someCola
can never be equal to an abstract type. Ideally I would like to do something like:
if (someCola is drinkType) ...
But the is
keyword only allows a class name after it.
Is there another way to check if someDrink
inherits a given type?
Refactoring isn't totally out of the question if you can suggest a better way to do this.
An abstract class cannot be inherited by structures. It can contain constructors or destructors.
Absolutely, an Abstract class can inherit from both non-abstract classes and other abstract classes.
How to declare abstract properties in C# An abstract property is declared by using the abstract modifier in a property declaration to indicate that the property is an abstract method and does not contain implementation.
Sure - you can use Type.IsAssignableFrom
:
if (drinkType.IsAssignableFrom(someDrink.GetType()))
Note that it's important that you don't get the target of the call and the argument the wrong way round. I have to consult the docs every time I use it, which is fortunately rarely :)
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