Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if objects type inherits an abstract type

Tags:

c#

types

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.

like image 918
jamesrom Avatar asked Dec 01 '11 06:12

jamesrom


People also ask

Can abstract class inherits?

An abstract class cannot be inherited by structures. It can contain constructors or destructors.

Can abstract class inherit abstract class?

Absolutely, an Abstract class can inherit from both non-abstract classes and other abstract classes.

Can we declare properties in abstract class C#?

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.


1 Answers

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 :)

like image 195
Jon Skeet Avatar answered Oct 20 '22 11:10

Jon Skeet