There are several different ways to create objects at runtime. Assuming that the assembly containing the type is already loaded then you can use this. Note that the type name must be fully qualified with the namespace name.
Code Snippet
object obj = Activator.CreateInstance(Type.GetType(strTypeName));
If the assembly is not loaded yet then you have to load the assembly first. Once you've got the type you can use reflection to interact with the object. For example to set the Name property of the object you'd do this:
Code Snippet
PropertyInfo prop = obj.GetType().GetProperty("Name");
prop.SetValue(obj, "Name1", null);
Note however that you'll find these objects limiting and slow. Reflection, although powerful, should only be used sparingly. The better scenario is to define an interface or base class from which all the objects you create will derive. This allows you to dynamically create the objects at runtime but still use early-binding to interact with them. So if you defined an interface like so:
Code Snippet
public interface IMyInterface
{
string Name { get; set; }
...
}
And all objects that you create at runtime implement this interface then you can create instances at runtime but still use early-binding like so.
Code Snippet
IMyInterface obj = Activator.CreateInstance(Type.GetType(strTypeName)) as IMyInterface;
if (obj != null)
{
obj.Name = "Name1";
};
More importantly though you get strong type-checking which is what you want anyway. Finally note that if the object does not implement the interface you can generate an error and ignore the object. This is how plugins normally work.
BTW please post general questions like this in the BCL forum (or similar). Please reserve the C# language forum for questions specifically about the C# language. I'm moving this post to the BCL forum where I think it is more appropriate.
Michael Taylor - 4/30/07
http://p3net.mvps.org