I’m trying to work out whether my webforms Page is a certain type.
I’ve got a number of base classes that inherit one another:
BasePage -> System.Web.UI.Page
CMSPage -> BasePage
Page -> CMSPage
In a custom UserControl, I need to get the the page, but only if it’s derived from CMSPage.
I’ve tried:
if(Page.GetType() == typeof(CMSPage))
But the value of GetType() just returns the class name of the page. It looks like I need to do:
if(Page.GetType().BaseType.BaseType == typeof(CMSPage))
To get the match working. However, some pages are at different BaseType levels before it reaches the type of CMSPage.
I could create a function like this to loop through each BaseType until it found the right one:
public static bool IsPageTypeOf(this System.Web.UI.Page page, Type targetType)
{
var pageType = page.GetType();
if (pageType == targetType)
return true;
while (pageType.BaseType != null)
{
if (pageType.BaseType == targetType)
return true;
pageType = pageType.BaseType;
}
return false;
}
But it feels messy. Is there a better way to do this?
Are you looking for:
Or if you know the type at compile time:
Or: