How to dyanamically instance a class from a string containing the class name?

How to dyanamically instance a class from a string containing the class name?

Post by Earl Teigr » Thu, 18 Sep 2003 23:26:24


In the exampe below, the constructor of the container class is passed the
string called "foo". Within the container class, I would like to create an
instance(s) of foo and add them to the ArrayList that is returned. (Once I
figure this out I will use reflection on the instance to do other stuff)

Anyway, How to I dyanamically create a new instance of a class from
ClassName string?

Thanks for your Help

Earl

private void Button1_Click(object sender, System.EventArgs e)
{
container mycontainer = new container("foo");
ArrayList fooArrayList = mycontainer.GetListOfObjects();
}

public class container
{
public string ClassName;
public container(object ClassName)
{
this.ClassName=ClassName;
}

public ArrayList GetListOfObjects()
{
ArrayList myArrayList = new ArrayList();
for(int i=1;i<10;i++)
{
//Convert.ToClass(ClassName) myClass = new Convert.ToClass(ClassName)
//myArrayList.Add(myClass);
}
return myArrayList;
}
}

public class foo
{
public string a="ahhhh";
public string b="bee";
public string c="see";
}
}
 
 
 

How to dyanamically instance a class from a string containing the class name?

Post by Jon Skee » Thu, 18 Sep 2003 23:37:09


Look at Type.GetType, Assembly.GetType and Activator.CreateInstance.

--
Jon Skeet - < XXXX@XXXXX.COM >
http://www.yqcomputer.com/ ~skeet
If replying to the group, please do not mail me too

 
 
 

How to dyanamically instance a class from a string containing the class name?

Post by Ignacio Ma » Thu, 18 Sep 2003 23:47:47

Hi,

Try Activator.CreateInstance( );

Cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation
 
 
 

How to dyanamically instance a class from a string containing the class name?

Post by Earl Teigr » Fri, 19 Sep 2003 05:01:24

Thanks for the replays

I have got it this far from what I have read but gettype is returning a null
value in the following code

private void Button1_Click(object sender, System.EventArgs e)
{
Type t = Type.GetType("foo"); //returns a null value
object classInstance = Activator.CreateInstance(t); //blows up because t
is null
}



public class foo
{
public string a="ahhhh";
public string b="bee";
public string c="see";
}
 
 
 

How to dyanamically instance a class from a string containing the class name?

Post by Michael » Fri, 19 Sep 2003 17:03:46

You need to use the full name of the type: GetType("yourNamespace.foo")

--
Michael R
XXXX@XXXXX.COM





null
t


the
an
I
Convert.ToClass(ClassName)