Alternative way of checking if an object is a match for any types in a given list

c#, class, inheritance, list, types

Solution

This code will do the job:

HashSet<Type> knownTypes = new HashSet<Type>()
{
    typeof(ArticlePage),
    typeof(ArticleListPage),
    // ... etc.
};

if (knownTypes.Contains(this.Page.GetType())
{
   //Do something fantastic
}

EDIT: As pointed by Chris, you may want to consider type inheritance to fully mimic the behavior of `is` operator. That's a bit slower but can be more useful for some purposes:

Type[] knownTypes = new Type[] 
{ 
    typeof(ArticlePage), 
    typeof(ArticleListPage),
    // ... etc.
};

var pageType = this.Page.GetType();
if (knownTypes.Any(x => x.IsAssignableFrom(pageType)))
{
    //Do something fantastic
}

Problem

``` if (this.Page is ArticlePage|| this.Page is ArticleListPage) { //Do something fantastic } ``` The above code works, but given the fact there could be many different classes I'd want to compare `this.Page` to, I would like to store the classes in a list and then perform a `.Contains()` on the list. How would I achieve this? Would I use `GetType()` somehow? Could I store a list of `Page` objects and then compare the types somehow? Note: You can assume all of the classes I'm comparing `this.Page` to extend `Page`.

Original source