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

E

Earl Teigrob

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";
}
}
 
J

Jon Skeet

Earl Teigrob said:
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?

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

Earl Teigrob

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";
}
 

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