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
.
Hard to comment on your exact usage, but a (relatively) easy way to do this and add a bit more tidyness to your checks (especially if you perform the same checks in multiple places) is to define an interface, have the relevant pages implement that interface, then do the check against that.
The empty interface:
So for example, your two page definitions might look like:
Then your check is essentially:
This has the benefit of not having to centrally store a list of "fantastic" pages; instead you just define it on the page class declarations and it becomes easy to add/remove "fantastic" pages.
Additionally, you may be able to move your "fantastic" behaviour to the interface/page:
Then in your checking code:
This way the implementation of something fantastic is handled elsewhere and not duplicated. Or you may move the checking and actions to a separate handling class altogether:
This code will do the job:
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:Although you should double reconsider using such code (because it seems to forget about polymorphism), you can use Reflection to check it:
IsAssignableFrom
will be true not only for specific class but also for all its subclasses, exacly likeis
operator.