Convert a string to Type

S

Saber

In an ASP.Net Website I've a string and want to convert that to Type.
Let's consider the string "Class1"
I tried: Type t = Type.GetType("Class1");

but it returns null.
 
M

Mark Fitzpatrick

Do you have the namespace that includes the class? You might also try the
full namespace for the class such as
Type.GetType("MyNameSpace.Classes.Class1"); The class has to be accessible
in order for it to create the type so usually the most common problem is a
missing namespace reference.
 
S

Saber

No, it is a website, and when you create a New Website,
you see there is no namespace like windows forms.
My class is in a subfolder of App_Code folder.
I read somewhere, in the Websites you should include full assembly.
I also tried:
System.Reflection.Assembly asm;

asm = System.Reflection.Assembly.GetAssembly(this.GetType());

Type[] typearray = asm.GetTypes();

after excuting, the typearray contains 3 items:
typearray[0].Value={Name = "_Default" FullName = "_Default"}
typearray[1].Value={Name = "default_aspx" FullName = "ASP.default_aspx"}
typearray[2].Value={Name = "FastObjectFactory_app_web_bdecafyb" FullName =
"__ASP.FastObjectFactory_app_web_bdecafyb"}


But where is Class1?! I think it is because I put this.GetType() as the
parameter of GetAssembly.
 
S

Saber

Thanks for replies,

I can't use typeof(Class1) or something similar,
because I don't know the string, and "Class1" is just an example.

I'll explain more,
There are lots of classes in business layer, they behave same and are
inherited from one base class.
There is a WebForm that users load it through menus, and the
classname given in QueryString.

Now we have something like it in the WebForm:

BaseClass baseclass;
string q=Request.QueryString["classname"];
switch (q)
{
case "ClassX":
BaseClass=new ClassX();break;
case "ClassY":
BaseClass=new ClassY();break;
case "ClassZ":
BaseClass=new ClassZ();break;
}

grid.DataSource=BaseClass().GetBrowsableData();

I want to get rid of this switch case statement, because the programmers
in our team want to add many classes.
In this situation, for each class they've to add a switch case and checkouts
and checkins and waitings!

So, it seems there is "no" way to do that in a WebSite. Right?
 
M

Mark Rae

The problem is that classes in the ap_code are compiled to separate
assembly

Which means, as I understand it, that any code in the App_Code folder gets
compiled twice...
 
G

Guest

Hi Saber,

There's another method to obtain type loaded from dynamically loaded
assemblies:
System.Web.Compilation.BuildManager.GetType(...)
 
R

Reuben Ahmed

Just tried the above method, and it does indeed work for classes in
appcode. Thanks!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top