ASP.Net and GetType()

Adam Driscoll picture Adam Driscoll · Oct 14, 2008 · Viewed 9k times · Source

I want to get a type of a "BasePage" object that I am creating. Every Page object is based off BasePage. For instance, I have a Login.aspx and in my code-behind and a class that has a method Display:

Display(BasePage page) {
    ResourceManager manager = new ResourceManager(page.GetType());
}

In my project structure I have a default resource file and a psuedo-translation resource file. If I set try something like this:

Display(BasePage page) {
    ResourceManager manager = new ResourceManager(typeof(Login));
}

it returns the translated page. After some research I found that page.GetType().ToString() returned something to the effect of "ASP_login.aspx" How can I get the actual code behind class type, such that I get an object of type "Login" that is derived from "BasePage"?

Thanks in advance!

Answer

Mark Cidade picture Mark Cidade · Oct 14, 2008

If your code-beside looks like this:

public partial class _Login : BasePage 
 { /* ... */ 
 }

Then you would get the Type object for it with typeof(_Login). To get the type dynamically, you can find it recursively:

Type GetCodeBehindType()
 { return getCodeBehindTypeRecursive(this.GetType());
 }

Type getCodeBehindTypeRecursive(Type t)
 { var baseType = t.BaseType;
   if (baseType == typeof(BasePage)) return t;
   else return getCodeBehindTypeRecursive(baseType);
 }