Gettype() returning a null

H

hardieca

Hi,

I have an .aspx page that needs to instantiate an object whose type in
not known until runtime. The definition of said object resides in
/App_code/CMS.cs

CMS.cs
==================
namespace CMS{
public interface IWindmill{
string emit
{get;}
}

public class MyObject : IWindmill{
string html;

public MyObject(){
html = "Hello World"
}

public string emit{
get { return html; }
}
}

In my webpage, I am trying to instantiate myObject dynamically, like
so:

Default.aspx.cs
============
protected void Page_Load(object sender, EventArgs e){
Type t = Type.GetType("CMS.MyObject"); //This object will vary and
won't be determined until runtime
CMS.IWindmill myObj = (CMS.IWindmill)Activator.CreateInstance(t);

MethodInfo m = myObj.GetType().GetMethod("get_emit");
if (m != null){
string s = (string)m.Invoke(myObj, null);
Response.Write(s);
}
}

My Type t will return null unless I include the CMS namespace in the
Default.aspx.cs file. Is there a way for me to return the proper value
if the object is defined in an external file? I understand I could
package the CMS namespace in an assembly and reference it through its
qualified name, but is there an easier and more direct way to get the
type in an external .cs file?

Regards,

Chris
 
J

Jon Skeet [C# MVP]

My Type t will return null unless I include the CMS namespace in the
Default.aspx.cs file. Is there a way for me to return the proper value
if the object is defined in an external file? I understand I could
package the CMS namespace in an assembly and reference it through its
qualified name, but is there an easier and more direct way to get the
type in an external .cs file?

Well, it will certainly be in *an* assembly by the time it's running.
Will you always want types from the same assembly, and do you know
*one* of those types at compile-time? If so, use typeof(...) to get
that type, then get the Assembly reference from that, then call
Assembly.GetType.
 

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